.so模块不在python中导入:动态模块没有定义init函数

时间:2010-11-06 07:52:07

标签: c++ python c python-c-api python-extensions

我正在尝试为C函数编写一个python包装器。在编写完所有代码并将其编译后,Python无法导入该模块。我按照here给出的例子。在修复一些拼写错误后,我在这里重现它。有一个文件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)

为什么我不能导入它?

1 个答案:

答案 0 :(得分:5)

由于您使用的是C ++编译器,因此函数名称为mangled(例如,g++ void initmyModule() _Z12initmyModulev#ifdef __cplusplus extern "C" { #endif #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); } #ifdef __cplusplus } // extern "C" #endif }。因此,python解释器将找不到模块的init函数。

您需要使用普通的C编译器,或使用extern "C"指令强制整个模块中的C链接:

{{1}}