Using swig 2.0.8 and python 3.2, running
swig -python -modern -py3 -o mymodule_wrap.c mymodule.i
produces a wrapper file that has
# define SWIG_init PyInit__mymodule
in there (note the two underscores between PyInit and mymodule).
Importing fails with
python3 -c "import mymodule"
Traceback (most recent call last):
File "<string>", line 1, in <module>
ImportError: dynamic module does not define init function (PyInit_mymodule)
(note the single underscore).
Manually deleting the underscore in mymodule_wrap.c and recompiling results in a working module.
In this question: SWIG and Python3 Import Error the python interpreter complained about not finding PyInit__module.
What’s wrong?
Make sure the extension module is named
_mymodule.pydnotmymodule.pyd.Explanation:
Given a SWIG
.ifile containing the declaration:SWIG will generate two files:
mymodule.pyis imported into Python viaimport mymoduleand loads_mymodule.pyd.mymodule_wrap.ccontains an entry point functionPyInit__mymodule. This source file must be linked into the final_mymodule.pyd.Python’s
import <module>statement looks for:<module>.pydwith entry pointPyInit_<module>.<module>.py.For a SWIG-generated extension,
import mymodulewill loadmymodule.py, which loads_mymodule.pydand looks correctly forPyInit__mymodule.If the wrong extension name is used,
import mymodulewill loadmymodule.pydand look incorrectly forPyInit_mymodule.