我正在尝试将SWIG与嵌入式Python 3.5.2一起使用。以下内容是作为Windows控制台应用程序构建的。当它尝试导入C ++端SWIG模块“_arpy”时,它无法初始化Python端SWIG模块“arpy.py”。我(可能不正确)理解C ++端“_arpy”模块应该已经由从main()调用的SWIG模块初始化函数加载,但似乎并非如此。
arpy.i:
%module arpy
%{
#include "arpy.h"
%}
%include <windows.i>
int test();
arpy.h:
#pragma once
int test();
swig -python -c++ arpy.i
生成:
arpy_wrap.cxx
arpy.py
main.cpp中:
#include <Python.h>
extern "C" PyObject* PyInit__arpy();
int main()
{
Py_Initialize();
PyInit__arpy(); // is this the right call to "import" the module?
PyRun_SimpleString("import arpy");
return 0;
}
int test()
{
return 1;
}
输出:
Traceback (most recent call last):
File "C:\Personal\Aue\Python\arpy.py", line 18, in swig_import_helper
return importlib.import_module(mname)
File "C:\3rdParty\lib\Python\Python-3.5.2\Lib\importlib\__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 986, in _gcd_import
File "<frozen importlib._bootstrap>", line 969, in _find_and_load
File "<frozen importlib._bootstrap>", line 956, in _find_and_load_unlocked
ImportError: No module named '_arpy'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Personal\Aue\Python\arpy.py", line 21, in <module>
_arpy = swig_import_helper()
File "C:\Personal\Aue\Python\arpy.py", line 20, in swig_import_helper
return importlib.import_module('_arpy')
File "C:\3rdParty\lib\Python\Python-3.5.2\Lib\importlib\__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
ImportError: No module named '_arpy'
Python正在运行arpy.py初始化代码,该代码在“_arpy”上使用importlib.import_module失败。在main()中调用PyInit__arpy()我认为应该通过CPython / C API“导入”SWIG生成的_arpy模块,但显然这一切都不起作用我的猜测。
答案 0 :(得分:1)
从这里的例子:( https://docs.python.org/3/extending/embedding.html) 我看到要将SWIG C ++模块导入为您需要的内置函数:
PyImport_AppendInittab(“_ arpy”,&amp; PyInit__arpy);
在调用Py_Initialize()
之前事情现在按预期工作。