开发者

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

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:

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


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.


On linux it can help to run strace in this case. Check that the name of the library python is searching for is the same as the name of the library you built.


The swig documentation mentions here:

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


In the interface file, SWIG suggests using:

#define SWIG_FILE_WITH_INIT


This turned to be unrelated to Python or the compiler, but was an incorrect compiler incantation (have to pay more attention while editing the Makefile).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜