Evgeny Lazin
Evgeny Lazin

Reputation: 9423

Can't import module created using SWIG

I'm trying to build python extension. I've create simple library that export single function. It's just a single file - testlib.c that implements function called 'apicall'. Then I create SWIG interface file:

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

Then I use this command to generate interface: swig -python -py3 -modern testlibpy.i

My setup.py looks like this:

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"],
      ) 

I'm building extension using command: python3.4 ./setup.py build_ext --inplace. Everything works fine. When I'm trying to import my new extension from python3.4 command-line, I've get following error:

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
>>>

Everything works fine for other python versions - 2.7 and 3.0. SWIG Version 1.3.40

Upvotes: 3

Views: 2720

Answers (1)

Simon Gibbons
Simon Gibbons

Reputation: 7194

In Python 3.2 the CObject API was removed. It was replaced with the Capsule API, which is also available for Python 2.7 and 3.1.

The older version of SWIG that you are using will be generating code using the CObject API that Python 3.4 doesn't have, hence causing the error when you import it and python can't find the function PyCObject_FromVoidPtr.

The solution would be to use a version of SWIG >= 2.0.4 to generate code for Python 3.2 and above.

From the SWIG Changelog

Version 2.0.4 (21 May 2011)

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

Upvotes: 3

Related Questions