我的C代码定义了一个常量,由于某种原因,我试图添加使用该常量的python代码(在pythoncode块中)。

演示.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

如果我在lookup块中注释掉pythoncode字典,那么一切正常:
[dave]$ python -c "import test; print test.i"
3

因此,至少在导入模块时,常量会显示出来。

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

swig 2.0.4,python 2.7。

最佳答案

Adding additional Python code的ojit_a状态:



因此,让我们跟踪生成的%pythoncode:

# 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

在定义test.py之前插入了%pythoncode。由于它是第一个也是唯一的外观,因此您可能需要直接使用i:
%pythoncode %{
# try to use the constant in some python code
lookup={'i': _test.cvar.i,}
%}

关于python - 在pythoncode块中使用模块定义的常量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31347788/

10-11 11:42