[Pythonmac-SIG] Using SWIG, C++, and OS X

Kent Quirk kent_quirk at cognitoy.com
Thu Jul 6 20:37:51 CEST 2006


Siddartha Krishnan wrote:
> I'm new to using SWIG for python. I am having several problems  
> creating a C++ extension module for python. I am using OS X 10.4 with  
> python 2.4 and SWIG 1.3.29 (using darwinports).
>
> I can use SWIG and distutils in order to make a C extension module  
> for python, however, I cannot do so for a C++ extension module - I  
> get an import error:
>
> mie-15-203:~/swig/class_test siddarthakrishnan$ python mymod.py
> Traceback (most recent call last):
>    File "mymod.py", line 5, in ?
>      import _mymod
> ImportError: Failure linking new module: /Users/siddarthakrishnan/ 
> SWIG/class_test/_mymod.so: Symbol not found: __ZN9SomeClassC1Eii
>    Referenced from: /Users/siddarthakrishnan/SWIG/class_test/_mymod.so
>    Expected in: dynamic lookup
>
> The setup.py file is as follows:
>
> # setup.py
> from distutils.core import setup, Extension
> setup (name = "_mymod",
> 	version = "1.0",
> 	maintainer = "Your Name",
> 	maintainer_email = "your.name at domain.org",
> 	description = "Sample Python C++ Extension",
> 	ext_modules = [Extension('_mymod',
> 				   sources=['mymod_wrap.cxx'])])
>
> Does anyone know how to create a setup.py file that works with c++  
> extension modules?
>
>   
I've never used SWIG, but I think your problem is related to name mangling.

Because C++ is designed to work with primitive linker technology (which 
uses names and only names for symbol resolution), it can't rely on the 
linker to be able to put together overloaded functions properly. If you 
have functions called abs(float) and abs(int), if the only name exported 
was abs, there'd be a conflict. So C++ "mangles" the names to include 
type information.

You can tell C++ to leave the names alone (giving them C linkage 
semantics) by using extern "C" like so:

extern "C" void myfunc(int x)
{
}

on the routines that you want to make available to Python. Understand 
that they'll have to be pure external functions, not members of classes.

You should probably read and understand this:

http://llama.med.harvard.edu/~fgibbons/doc/SWIG1.3.10/Manual/SWIG.html

If you're into C++ and want to use the power of C++ in conjunction with 
Python, consider using boost::python instead of SWIG.

    Kent



More information about the Pythonmac-SIG mailing list