SWIG + Python without DLL

SWIG + Python without DLL

本文关键字:DLL without Python SWIG      更新时间:2023-10-16

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

我已经设置了我的接口API。文件如下:
%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有问题。我想是我做错了什么设置,但如果有人有任何建议,我将不胜感激!

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

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

我为你整理了一个完整的例子。使用SWIG模块:

%module test
%inline %{
void doit(void) {
  printf("Hello worldn");
}
%}

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

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。(我用我对这个问题的回答作为参考点)。这个测试我的C是:
#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;
}

编译和运行时有效:

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调用,它不会像我希望的那样工作。