【问题标题】:SWIG + Python without DLL没有 DLL 的 SWIG + Python
【发布时间】:2015-05-19 17:16:21
【问题描述】:

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

我的接口 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 有问题。我想我做错了某种设置,但如果有人有任何建议,他们将不胜感激!

【问题讨论】:

    标签: python c++ python-3.x swig


    【解决方案1】:

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

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

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

    %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 是:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-21
      • 1970-01-01
      • 2020-02-07
      相关资源
      最近更新 更多