8

我正在尝试为 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)

为什么我不能导入?

4

1 回答 1

5

由于您使用的是 C++ 编译器,因此函数名称将被修改(例如,我的g++修改void initmyModule()_Z12initmyModulev)。因此,python 解释器不会找到您模块的 init 函数。

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

#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 
于 2010-11-06T12:21:28.397 回答