SWIG + Python without DLL
SWIG + Python without DLL
在过去的几天里,我一直在努力导入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调用,它不会像我希望的那样工作。
相关文章:
- 挂起和取消挂起一个文件DLL
- std::threads可以从Windows DLL中的全局变量创建/销毁吗?
- 导入库可以跨dll版本工作吗
- 从C++dll访问C#中的一行主要参数
- 链接到自行创建的dll失败
- 为什么使用 P/Invoke 调用 dll 时,某些计算机中的 LoadLibrary 失败?
- 在调用FreeLibrary后,释放动态链接到具有相同版本的CRT堆的DLL的内存
- 如何指定我希望我的LIB链接到的DLL文件?-Visual Studio 2019
- 如何将图像传输到c++(dll)中的缓冲区,然后在c#的缓冲区中读/写
- C++:将外部库链接到dll库
- 在 Windows 上,是否可以让 dll 在不使用 PATH 环境变量的情况下在另一个文件夹中查找依赖项?
- 不同的Visual Studio版本中缺少.dll
- 从DLL中删除类的实例
- 如何包装第三方DLL在R中使用
- dynamic_cast without RTTI
- 使用c#访问c++dll中带有char*参数的函数时发生AccessViolationException
- 系统.将数组移交给c#中动态加载的c++DLL时发生AccessViolationException
- 为什么导入Mixed native/CLR lib.dll的本机C++应用程序没有在Mixed lib.dll中的外部变
- OpenSSL win32 without libeay32.dll
- SWIG + Python without DLL