我想写一个C函数的python包装。编写完所有代码并编译后,Python无法导入模块。我按照给出的例子here。在修复了一些错别字之后,我在这里重现了它。有一个文件mymodule.c的:.so模块没有在python中导入:动态模块没有定义初始化函数
#include <Python.h>
/*
* Function to be called from Python
*/
static PyObject* py_myFunction(PyObject* self, PyObject* args)
{
char *s = "Hello from C!";
return Py_BuildValue("s", s);
}
/*
* Bind Python function names to our C functions
*/
static PyMethodDef myModule_methods[] = {
{"myFunction", py_myFunction, METH_VARARGS},
{NULL, NULL}
};
/*
* Python calls this to let us initialize our module
*/
void initmyModule()
{
(void) Py_InitModule("myModule", myModule_methods);
}
因为我在Mac上使用MacPorts的蟒蛇,我编译为
$ g++ -dynamiclib -I/opt/local/Library/Frameworks/Python.framework/Headers -lpython2.6 -o myModule.dylib myModule.c
$ mv myModule.dylib myModule.so
不过,我得到一个错误,当我尝试导入它。
$ ipython
In[1]: import myModule
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
/Users/.../blahblah/.../<ipython console> in <module>()
ImportError: dynamic module does not define init function (initmyModule)
为什么我不能导入它?
你的代码似乎有点乱码。 – 2010-11-06 07:53:48
@Ignacio:我只是想跟着例子。有没有更简单的例子可以指向我? – highBandWidth 2010-11-06 07:55:46
顶部框中的代码是否真正反映了您在源文件中的内容? – 2010-11-06 07:56:50