Swig – Python – C / C++

Tutorials

http://www.penzilla.net/tutorials/python/swig/

http://en.opensuse.org/images/e/eb/Kkaempf_KnowledgeSharing_Swig.pdf

Compiling Swig

The source can be obtained at http://www.swig.org/download.html

After that sh configure and make did the job…

Under Ubuntu 10.10  I had to install sudo apt-get install libpcre3-dev first.

Using Swig

First generate the interface file (private remark: not on the cluster, swig not installed)

swig -python test.i

This generates test_wrap.c. Now we compile

gcc -fPIC -c test.c test_wrap.c -I/usr/include/python2.6 -I/usr/lib/python2.6

see http://ubuntuforums.org/showthread.php?t=643081 for the fPIC option.

Then we link the library

ld -shared -o _test.so test.o test_wrap.o  -lgsl -lgslcblas -lm -lc

If we want to include other libraries into test.c we can do this in the usual way by adding an additional flag to the lib.

It is better to do everything in one step. Then library constructor/destructors are also executed which is convenient.

cc -fPIC  scorer.c scorer_wrap.c -I$(INCLUDES) -I/usr/include/python2.6 -I/usr/ib/python2.6 -lgsl -lgslcblas -shared -Wl,-soname,_scorer.so  -o _scorer.so

Defining the interface well

It is important to include the header file here, otherwise the behaviour is quite strange. I can compile but the returned values are crap.

%module spinflip
%{
#include “test.h”
%}
double    test (double t);

Swig and pointers / more complicated objects

C-pointer:

http://www.swig.org/Doc1.1/HTML/Typemaps.html (OLD SWIG)

http://www.swig.org/Doc2.0/Library.html#Library_nn4 (NEW SWIG)

http://stackoverflow.com/questions/1583293/using-swig-with-pointer-to-function-in-c-struct

Swig and C++

http://www.swig.org/Doc2.0/SWIGPlus.html#SWIGPlus

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: