1

My C code defines a constant, I'm trying to add python code (in a pythoncode block) that uses that constant, for some reason this doesn't work.

Demonstration .i file:

%module test
%{
// c code defines a static constant
static const int i=3;
%}

// declare the constant so that it shows up in the python module
static const int i;

%pythoncode %{
# try to use the constant in some python code
lookup={'i':i,}
%}

Here's the error:

[dave]$ python -c "import test"
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "test.py", line 70, in <module>
    lookup={'i':i,}
NameError: name 'i' is not defined

If I comment out the lookup dictionary in the pythoncode block, everything works fine:

[dave]$ python -c "import test; print test.i"
3

so at least when I import the module the constant shows up.

How can I "see" the C-defined constants in my pythoncode block?

swig 2.0.4, python 2.7.

2 Answers 2

2

Adding additional Python code states for %pythoncode:

This code gets inserted in to the .py file created by SWIG.

So let's tail the generated test.py:

# try to use the constant in some python code
lookup={'i':i,}

# This file is compatible with both classic and new-style classes.

cvar = _test.cvar
i = cvar.i

The %pythoncode was inserted before i is defined. Since it's the first and only appearance, you might need to use _test.cvar.i directly instead:

%pythoncode %{
# try to use the constant in some python code
lookup={'i': _test.cvar.i,}
%}
Sign up to request clarification or add additional context in comments.

Comments

1

Another workaround is to defer referencing the variable until after the module completes loading, by using a function:

%pythoncode %{
def lookup( key ){
     mp={'i':i}
     return mp[key]
%} 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.