2010-11-06 44 views
7

我想写一个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) 

为什么我不能导入它?

+0

你的代码似乎有点乱码。 – 2010-11-06 07:53:48

+1

@Ignacio:我只是想跟着例子。有没有更简单的例子可以指向我? – highBandWidth 2010-11-06 07:55:46

+0

顶部框中的代码是否真正反映了您在源文件中的内容? – 2010-11-06 07:56:50

回答

5

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

您需要可以使用普通的C编译器,或迫使C链接整个模块的extern "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 
+2

文档中给出的'PyMODINIT_FUNC'宏将为您处理。 – 2010-11-06 12:35:40

+0

@ IgnacioVazquez-Abrams:请您详细说明如何执行您的解决方案?谢谢。 – RDK 2012-11-11 02:28:43

相关问题