I am trying to wrap a function foo in test.cpp
with swig. I have a header foo.h
which contains the declaration of the function foo. test.cpp
is dependent upon a external header ex.h
and shared object file libex.so
located in /usr/lib64
I followed the blog post from here.
I am able to build the module with python setup.py build_ext --inplace
. However when I try to import it I get the following error and I am not sure what I am missing as most others questions with this error do not use a setup.py
file. Below is an example of what I currently have.
The Error on importing _foo:
>>> import _foo
ImportError: dynamic module does not define init function (init_foo)
test.i
%module foo
%{
#pragma warning(disable : 4996)
#define SWIG_FILE_WITH_INIT
#include "test.h"
%}
%include <std_vector.i>
%include <std_string.i>
%include "test.h"
test.cpp
#include "ex.h"
void foo(int i){
return;
};
test.h
#include "ex.h"
void foo(int i);
setup.py
try:
from setuptools.command.build_ext import build_ext
from setuptools import setup, Extension, Command
except:
from distutils.command.build_ext import build_ext
from distutils import setup, Extension, Command
foo_module = Extension('_foo',
sources=['foo.i' , 'foo.cpp'],
swig_opts=['-c++'],
library_dirs=['/usr/lib64'],
libraries=['ex'],
include_dirs = ['/usr/include'],
extra_compile_args = ['-DNDEBUG', '-DUNIX', '-D__UNIX', '-m64', '-fPIC', '-O2', '-w', '-fmessage-length=0'])
setup(name='mymodule',
ext_modules=[foo_module],
py_modules=["foo"],
)
I had the same error, however it was due to which python was being in use. I was using a system with python2.7, python3.4 and python3.5. Only "python3" (symlinked to python3.5) worked. Importing with any of the other pythons gave the " ImportError: dynamic module does not define init function" error.
Is looks like there is some inconsistency in the use of foo
and _foo
, as the wrap file is generated compiled and linked in.
Try changing the module name in test.i
from
%module foo
to
%module _foo
or adjusting the Extension declaration in your setup.py
from
Extension('_foo',
to
Extension('foo',
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With