SWIG and C++ shared library

Veles picture Veles · Apr 12, 2012 · Viewed 10.6k times · Source

I have a C++ library (let's call it mylib) which compiles to libmylib.so file in /usr/local/lib and I have a bunch of header files in a directory called my lib in /usr/local/include.

Now the thing I wanted to do (for starters) is just use one of the header files (it contains information about a class my library is offering) with SWIG to generate the mylib_wrap.cxx file and then compile it and link it against the existing mylib.so. So that I can instance my class in Python.

Is this the right approach/idea? How would the compile and linking command look like (not exactly of course)? I am trying to generate a Python binding.

Answer

Flexo picture Flexo · Apr 12, 2012

I've put together a complete example for you:

Header file:

(mylib.h)

class Foo {
};

void bar(const Foo&);

Implementation:

#include "mylib.h"
#include <iostream>

void bar(const Foo& f) {
  std::cout << &f << std::endl;
}

Compile the library:

g++ -fPIC -Wall -Wextra -shared mylib.cc -o libmylib.so

SWIG interface to wrap the library:

%module mylib

// Make mylib_wrap.cxx include this header:
%{
#include "mylib.h"
%}

// Make SWIG look into this header:
%include "mylib.h"

Compile Python module:

swig -Wall -c++ -python mylib.i  
g++ -fPIC -Wall -Wextra -shared mylib_wrap.cxx -o _mylib.so -L. -lmylib -I/usr/include/python2.7/ -lpython2.7 

Note that we linked the Python module against the library. If it wasn't in the current directory you'd need to specify the library path. SWIG expects the native part of Python module to be called _module.so

Run

LD_LIBRARY_PATH=. python                                                 
Python 2.7.2+ (default, Nov 30 2011, 19:22:03) 
[GCC 4.6.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import mylib
>>> i=mylib.Foo()
>>> mylib.bar(i)
0x28cc100
>>> mylib.bar(i)
0x28cc100
>>> mylib.bar(mylib.Foo())
0x28b3b10

Here I made sure the shared objects we just built are on the library path by setting LD_LIBRARY_PATH appropriately.