2015-07-10 75 views
1

我的C代码定义了一个常量,我试图添加使用该常量的Python代码(在pythoncode块中),由于某些原因,这不起作用。在Python代码块中使用模块定义的常量

示范.i文件:

%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,} 
%} 

这里的错误:

[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 

如果我注释掉pythoncodelookup字典,一切工作正常:

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

所以至少当我重要时常数显示模块。

如何在我的pythoncode块中“查看”C定义的常量?

swig 2.0.4,python 2.7。对于%pythoncode

回答

2

Adding additional Python code状态:

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

让我们尾部产生test.py:定义i之前

# 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 

%pythoncode插入。因为它是第一个也是唯一的外观,您可能需要使用_test.cvar.i,而不是直接:

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

另一个解决办法是推迟引用变量,直到模块完成加载,通过使用功能后:

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