2015-05-19 59 views
1

在过去的几天里,我一直在努力导入一个SWIG生成的模块。我正在使用Python 3.4.1和SWIG 3.0.5。SWIG +没有DLL的Python

我设置我的界面API.i文件,如下所示:

%module Root 
%{ 
#include "Root.h" 
%} 
%include "Root.h" 

没什么特别的头,因为我只是想获得一些事情。将生成一个API_wrap.cxx文件,并且Root.py文件也会生成。到现在为止还挺好。

现在,基于以下网站:https://docs.python.org/2/faq/windows.html#how-can-i-embed-python-into-a-windows-application他们暗示我可以通过以下操作直接加载模块(都在同一个EXE,而不需要有一个单独的DLL):

Py_Initialize(); 
PyInit__Root(); 
PyRun_SimpleString("import Root"); 

如果我还没有Root.py文件,导入工作正常,但是然后我失去了影子/代理类(其中,我猜测)。如果我确实有Root.py文件,我得到以下错误:

“导入无法找到模块,或无法在模块中找到名称。”

我注意到如果我在Root.py文件中写了乱码,我得到一个语法错误,这很明显生成的Root.py有问题。我想有些设置我做错了,但如果有人有任何建议,他们将不胜感激!

回答

0

我想你会想用PyImport_AppendInittab正确地注册内置模块。

您还需要致电PySys_SetPath()来设置模块本身的Python代理部分的路径。

我为你整理了一个完整的例子。随着夜风模块:

%module test 

%inline %{ 
void doit(void) { 
    printf("Hello world\n"); 
} 
%} 

,我们可以使用编译和验证独立:

swig2.0 -Wall -python test.i 
gcc -Wall -Wextra -shared -o _test.so test_wrap.c -I/usr/include/python2.7 
Python 2.7.6 (default, Mar 22 2014, 22:59:38) 
[GCC 4.8.2] on linux2 
Type "help", "copyright", "credits" or "license" for more information. 
>>> import test 
>>> test.doit() 
Hello world 

然后,我们可以写我们的C代码中嵌入了Python。 (我用我的回答to this question作为参考点)。我给这家检验C是:

swig2.0 -Wall -python test.i 
gcc -Wall -Wextra -shared -c -o test_wrap.o test_wrap.c -I/usr/include/python2.7 
gcc run.c test_wrap.o -o run -Wall -Wextra -I/usr/include/python2.7 -lpython2.7 
./run 
Hello from Python 
Hello world 

如果我跳过要么设置路径或AppendInittab打电话,我会希望它不工作:

#include <Python.h> 
void init_test(void); 

int main() { 
    PyImport_AppendInittab("_test", init_test); // Register the linked in module 
    Py_Initialize(); 
    PySys_SetPath("."); // Make sure we can find test.py still 
    PyRun_SimpleString("print 'Hello from Python'"); 
    PyRun_SimpleString("import test"); 
    PyRun_SimpleString("test.doit()"); 
    return 0; 
} 

编译和运行时,此工作。