1

I was provided with a c library wave.so, with a function interfaced defined, I follow the guide here

https://stackoverflow.com/a/5868051/2789784

and it works. However, when I made the script to be a file MyModule.py, and try to import by

import MyModule

Then it gives me this error.

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: dynamic module does not define init function (initwave)

Why does this happen? How should I fix it?

FIXED: so I have both MyModule.py and MyModule.so at the same folder, python tried to load MyModule.so instead of MyModule.py, and of course he cannot be successful, change the name of MyModule.py to wave.py and

import wave 

solves the problem. So basically if you just want to call some c++ library function, you really just need a python script wrapper and that's it, no c-programming. And I can use my c++ shared library for other application too.

Community
  • 1
  • 1
user40129
  • 763
  • 1
  • 5
  • 15
  • 1
    Is your `.so` also called `MyModule.so`? That would explain Python picking up the wrong file. – millimoose Sep 26 '13 at 17:10
  • Haha, you are right on, I just come back to try to fix my stupidity before someone else spots it, and here you are, spotting it. – user40129 Sep 26 '13 at 17:19

1 Answers1

1

When you write an extension module in C there must be a module init function. If your module is called wave, there must be a function called initwave in the extension module. A simple example would be:

static PyMethodDef methods[] = {
    /* methods go here, if any */
    {NULL, NULL, 0, NULL}
};

PyMODINIT_FUNC initwave(void){
Py_InitModule3("wave", methods, "this is the doc string");
}

Then compile the extension with something like:

Extension('wave',
    ['source_file.c', 'another_source_file.c'],
)

The extension module that you can import is called wave.so, (I don't know if renaming it is safe, but its definitely no good idea) In your python script MyModule.py simply do:

import wave 
dastrobu
  • 1,600
  • 1
  • 18
  • 32
  • By following that guide, I was able to call the function in wave.so without writing c code. Why cannot just write some wrapper function in python and use that as my module.py file and import. – user40129 Sep 26 '13 at 16:37
  • 1
    You can, by writing a Cython wrapper, as described in in your link, or you could just use [ctypes](http://docs.python.org/2/library/ctypes.html?highlight=ctypes#ctypes). Anyway, your quoted error message indicates that at some point Python is assuming that `wave.so` is a python C extension, which it isn't. How this comes, I cannot tell from the given information. Try to narrow the problem down and give additional information, which will make it easier to help. – dastrobu Sep 26 '13 at 16:55