Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

python

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.

like image 543
djc Avatar asked Feb 18 '11 13:02

djc


4 Answers

I had the same issue. At compile time:

  • path to the Python header: OK
  • path to the Python library: OK
  • link against the Python library: OK
  • link against needed third parties libraries/object files: OK

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! :)

like image 129
lin3 Avatar answered Nov 04 '22 04:11

lin3


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.

like image 8
Klaas Avatar answered Nov 04 '22 05:11

Klaas


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.

like image 5
dividebyzero Avatar answered Nov 04 '22 03:11

dividebyzero


Make sure you include your _wrap.cxx. It seems to me it doesn't get compiled into your module.

like image 1
Jackie Lee Avatar answered Nov 04 '22 05:11

Jackie Lee