无法导入使用 SWIG 创建的模块

Can't import module created using SWIG

我正在尝试构建 python 扩展。我创建了导出单个函数的简单库。它只是一个文件 - testlib.c 实现了名为 'apicall' 的函数。然后我创建 SWIG 接口文件:

%module testlibpy                      
void apicall(const char* message);

然后我用这个命令生成界面:swig -python -py3 -modern testlibpy.i

我的 setup.py 看起来像这样:

from distutils.core import setup, Extension


example_module = Extension('_testlibpy',
                           sources=['testlibpy_wrap.c', 'testlib.c'],)

setup (name = 'testlibpy',
       version = '0.1',
       author      = "SWIG Docs",
       description = """Simple swig example from docs""",
       ext_modules = [example_module],
       py_modules = ["testlibpy"],
      ) 

我正在使用命令构建扩展:python3.4 ./setup.py build_ext --inplace。一切正常。当我尝试从 python3.4 命令行导入我的新扩展时,出现以下错误:

Python 3.4.2 (default, Feb 18 2015, 04:50:08)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-48)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import testlibpy
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File ".../sandbox/swigtest/testlibpy.py", line 24, in <module>
    _testlibpy = swig_import_helper()
  File ".../sandbox/swigtest/testlibpy.py", line 20, in swig_import_helper
    _mod = imp.load_module('_testlibpy', fp, pathname, description)
  File ".../swt/install/python-3.4.2/lib/python3.4/imp.py", line 243, in load_module
    return load_dynamic(name, filename, file)
ImportError: .../sandbox/swigtest/_testlibpy.cpython-34m.so: undefined symbol: PyCObject_FromVoidPtr
>>>

其他 python 版本 - 2.7 和 3.0 一切正常。 SWIG 版本 1.3.40

在 Python 3.2 中的 CObject API was removed. It was replaced with the Capsule API,也可用于 Python 2.7 和 3.1。

您使用的旧版 SWIG 将使用 Python 3.4 没有的 CObject API 生成代码,因此在您导入它时会导致错误 python 找不到函数 PyCObject_FromVoidPtr.

解决方案是使用 SWIG >= 2.0.4 的版本为 Python 3.2 及更高版本生成代码。

来自SWIG Changelog

Version 2.0.4 (21 May 2011)

2011-04-09: szager
[Python] Applied patch #1932484: migrate PyCObject to PyCapsule.