Tag Archives: swig

I had a hell of time doing creating Swig wrappers to access my C++ code/data/method from Python :(

After all those trail and errors of an evening i have tumbled upon a solution, which i should presume could be helpful and simple to many.

Pls note: I tried this on Archlinux, 32bit machine. The compilation steps may differ for various platforms

First lets see my example.h code…

//example.h
#include <iostream>
using namespace std;

class example{
public:
void foo();
void bar();
};

Here is my example.cpp file …

//example.cpp
#include "example.h"
void example::foo(){
cout<<"FOO";
}
void example::bar(){
cout<<"BAR";
}

And finally my Swig interface file example.i

%module example
%{
#include "example.h"
%}
%include "example.h"

Then its a few simple steps for compilation…

$ swig -c++ -python example.i
$ g++ -c example.cpp
$ g++ -c example_wrap.cxx -I/usr/local/include/python2.4
$ g++ -shared example.o example_wrap.o -o _example.so

Now ‘python’ and ….

>>> from example import example
>>> e=example()
>>> print e.foo()
FOO
>>> print e.bar()
BAR

Thats it! Now, u r up and running with Swig/C++.