我正在尝试为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
原文地址:https://www.jb51.cc/c/119032.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。