ImportError: the dynamic module does not define the init function, but it does

I am trying to write a binding for a C ++ provider library. I have successfully used fragments such as below to define init functions in other modules, but it does not seem to work in this: it compiles fine, but throws ImportError as soon as I try to import it into a test script. What could be wrong here?

#ifndef PyMODINIT_FUNC /* declarations for DLL import/export */ #define PyMODINIT_FUNC void #endif PyMODINIT_FUNC initclient(void) { PyObject* m; ClientType.tp_new = PyType_GenericNew; if (PyType_Ready(&ClientType) < 0) return; m = Py_InitModule3("client", client_methods, "Client module"); Py_INCREF(&ClientType); PyModule_AddObject(m, "Client", (PyObject *) &ClientType); } 

This is 32-bit Linux, with gcc 4.4.4.

+8
c ++ python
source share
8 answers

This turned out to be unrelated to Python or the compiler, but it was the wrong compiler spell (more attention should be paid when editing the Makefile).

-3
source share

I had the same problem. At compile time:

  • Python header path: OK
  • Python library path: OK
  • Python library reference: OK
  • Link to required third-party libraries / object files: OK

I just forgot to compile the C file, which defines my module ... Sigh ...

So yes, the first thing to check is: your makefile or your compilation team! :)

+7
source share

I had the same error message, but that was because I renamed my .c file and forgot to update the name inside the code. "Initxxx" and the argument inside it.

+5
source share

Make sure you are not mixing Python versions. In Python version 2, the init function was called Init_, and in version 3 this function is called PyInit _

In my case, this happened when SWIG 3.0.2 used Python 3.4 to create bindings, while my Python IDE was called the Python 2.7 interpreter.

You can see the difference in the generated .cxx file:

 #if PY_VERSION_HEX >= 0x03000000 # define SWIG_init PyInit__<modulename> #else # define SWIG_init init_<modulename> #endif 

On linux, you can also use the following command to test .so export:

 nm -D <modulename> | grep <modulename> 

This will give you the name of the init function inside your library.

+5
source share

Make sure you include your _wrap.cxx. It seems to me that it does not compile into your module.

+1
source share

On linux, this can help run strace in this case. Make sure the name of the python library executable matches the name of the library you created.

0
source share

The swig documentation mentions here :

This error almost always occurs when a bad name is assigned to a shared object file. For example, if you created the example.so file instead of _example.so, you will get this error.

0
source share

In the interface file, SWIG suggests using:

 #define SWIG_FILE_WITH_INIT 
0
source share

All Articles