Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SWIG + setup.py: ImportError: dynamic module does not define init function (init_foo)

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"],
      )
like image 681
pyCthon Avatar asked Mar 11 '16 19:03

pyCthon


2 Answers

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.

like image 193
A guest Avatar answered Nov 19 '22 19:11

A guest


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',  
like image 4
Thomas Avatar answered Nov 19 '22 17:11

Thomas