2015-07-10 114 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] 
%}