2010-11-04 114 views
5

我无法在Windows上重现基本的SWIG示例。 我的错误在SWIG文档中有说明,我相信我会提供他们提到的2个修复程序。对于这个错误:swig no module named _example

>>> import example 
Traceback (most recent call last): 
    File "<stdin>", line 1, in ? 
    File "example.py", line 2, in ? 
    import _example 
ImportError: No module named _example 

的SWIG文档中明确规定:

忘了前面的下划线(_)。 。

忘了前面的下划线(_)>如果您收到此消息,这意味着

you either forgot to compile the wrapper code into an extension module or you didn't give the extension module the right name. Make sure that you compiled the wrappers into a module called example.so. And don't forget the leading underscore ().forget the leading underscore (_).

,我相信我有最新的包装对象建立联系,我已经tryied:“_example” ,“_example.so”,“example.dll”,“example.so”,“example.dll”,甚至一次全部生成,并且生成的“example.py”与共享库位于同一文件夹中,并且python路径包含这个目录,并且忽略了前导下划线()。

的例子:

//example.h 
int foo_sum(int a, int b); 

//example.cpp 
int foo_sum(int a, int b) { 
    return a + b; 
} 

//example.i 
%module example 
%{ 
#include "example.h" 
%} 

#include "example.h 

和构建命令:

gcc -IV:\temp\example\external\include\Python -O3 -Wall -c -fmessage-length=0 -oexample_wrap.o ..\example_wrap.c 
g++ -IV:\temp\example\external\include\Python -O3 -Wall -c -fmessage-length=0 -oexample.o ..\example.cpp 
g++ -LV:\temp\example\external\lib -shared -oexample.dll example_wrap.o example.o -lpython26 

即使我不使用-O3它仍然无法正常工作(我粘贴构建从发布的配置命令)

我也试过这个问题,并没有成功:

>>> import sys 
>>> sys.path.append("/your/module/path") 
>>> import example 

编辑:

显然,如果你将其重命名为“_example.pyd”,但加载的模块不包含我的“foo_sum”功能,它加载的dll

编辑: 现在的工作,我现在用的extern“C”和不包括.i文件中的标题

+11

你应该在答案中写下你的答案,并将其标记为正确 - (你得到一个自学者徽章)。它阻止了像我这样的人在没有回答的列表上查找你的问题,只是为了发现一切正常。 – Tom 2011-01-29 15:54:14

回答

0

我发现你必须将C++从.dll生成的库文件重命名为.pyd。我不记得是否需要在苹果上重命名它。而你想暴露给python的函数在它之前必须有extern“C”。否则,编译器不会使该函数在库外可访问。另外如果我记得你需要将返回值封装在Py_value中,如果你想在python中使用它们。

2

库的文件名必须是* .pyd。我想你已经生成了一个包装器代码并将其链接在一起。

0

我发现(在Windows中),如果你制作一个dll,它必须被调用_modulename.pyd 这个库(_modulename.pyd),原始的C++模块myapp.dll和生成的modulename.py必须是在路径中以及pythonxx.exe