我正在尝试为 C 函数编写一个 python 包装器。编写完所有代码并编译后,Python 无法导入模块。我正在按照此处给出的示例进行操作。在修正了一些错别字后,我在这里复制它。有一个文件 myModule.c:
#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);
}
由于我在使用 Macports python 的 Mac 上,我将其编译为
$ 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)
为什么我不能导入?