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

我为什么不能导入它?

有帮助吗?

解决方案

由于您使用的是C ++编译器,函数名称将为 陷入困境 (例如,我的 g++ 麦格尔 void initmyModule() 进入 _Z12initmyModulev)。因此,Python解释器找不到您的模块的初始功能。

您需要使用普通的C编译器,或者在整个模块中强制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 
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top