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.
1 Answer 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
2 Comments
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.
.soalso calledMyModule.so? That would explain Python picking up the wrong file.