I'm trying to write a binding for a vendor C++ library. I've successfully used snippets such as the below to define init functions in the other modules, but in this one it doesn't seem to work: it compiles fine, but throws the 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 on 32-bit Linux, with gcc 4.4.4.
I had the same issue. At compile time:
I just forgot to compile the C file that defines my module... Sigh...
So yeah, first thing to check: your makefile or your compilation command! :)
Make sure you don't mix Python versions. In Python version 2 the init function was called Init_, while in version 3 this function is called PyInit_
In my case this was happening when SWIG 3.0.2 used Python 3.4 to generate bindings, while my Python IDE 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 check your .so exports:
nm -D <modulename> | grep <modulename>
This will give you the name of the init function within your library.
I had the same error message, but it was because I renamed my .c file, and forgot to update the name inside the code. The "initxxx" function and an argument inside it.
Make sure you include your _wrap.cxx. It seems to me it doesn't get compiled into your module.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With