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

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

为什么我不能导入它?

解决方法

由于您使用的是C编译器,因此函数名称将为 mangled(例如,我的g mangles 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,s);
}

/*
 * Bind Python function names to our C functions
 */
static PyMethodDef myModule_methods[] = {
    {"myFunction",myModule_methods);
}

#ifdef __cplusplus
}  // extern "C"
#endif

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...