SWIG + setup.py:ImportError:动态模块没有定义init函数(init_foo)

pyC*_*hon 10 c++ python linux swig python-2.7

我试图test.cpp用swig 包装函数foo .我有一个标题foo.h,其中包含函数foo的声明.test.cpp是依赖于外部报头ex.h和共享对象文件libex.so位于/usr/lib64

从这里关注了博文.

我能够用它构建模块python setup.py build_ext --inplace.但是,当我尝试导入它时,我得到以下错误,我不知道我错过了什么,因为大多数其他问题与此错误不使用setup.py文件.以下是我目前拥有的一个例子.

导入_foo时出错:

>>> import _foo

ImportError: dynamic module does not define init function (init_foo)
Run Code Online (Sandbox Code Playgroud)

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"
Run Code Online (Sandbox Code Playgroud)

TEST.CPP

#include "ex.h"

void foo(int i){
    return;
};
Run Code Online (Sandbox Code Playgroud)

test.h

#include "ex.h"

void foo(int i);
Run Code Online (Sandbox Code Playgroud)

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"],
      )
Run Code Online (Sandbox Code Playgroud)

Tho*_*mas 4

看起来fooand的使用存在一些不一致_foo,因为包装文件是在编译和链接中生成的。

尝试更改模块名称test.ifrom

%module foo
Run Code Online (Sandbox Code Playgroud)

%module _foo
Run Code Online (Sandbox Code Playgroud)

或调整您的扩展setup.py声明

Extension('_foo',
Run Code Online (Sandbox Code Playgroud)

Extension('foo',  
Run Code Online (Sandbox Code Playgroud)