.so doesn't import in python: dynamic module doesn't define init function

I am trying to write a python shell for function C. After writing all the code and compiling it, Python cannot import the module. I follow the example here . I reproduce it here after correcting some typos. File 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); } 

Since I am on a Mac with Python Macports, I will compile it as

 $ g++ -dynamiclib -I/opt/local/Library/Frameworks/Python.framework/Headers -lpython2.6 -o myModule.dylib myModule.c $ mv myModule.dylib myModule.so 

However, I get an error when trying to import it.

 $ 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) 

Why can't I import it?

+7
c ++ c python python-c-api python-extensions
source share
1 answer

Since you are using the C ++ compiler, function names will be mutilated (e.g. my g++ mangles void initmyModule() ) in _Z12initmyModulev ). Therefore, the python interpreter will not find your init init function.

You need to either use a simple C compiler, or force a C connection in the entire module with the extern "C" directive:

 #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 
+5
source share

All Articles