Tuesday, January 4, 2011

SWIG ; Lets u call C++ functions from Python

SWIG simply put is a program that allows you to call C/C++ functions from Python. What that essentially means you get both the speed of C/C++ and the amazing scriptability of Python. Installing SWIG on debian systems is simple as

$ sudo apt-get install swig

Python.h which is required next can be got by

$ sudo apt-get install build-essential

Lets say you have a C++ file euler.cpp. In order to use SWIG include the following header file #include </usr/include/python2.6/Python.h> at the first line of euler.cpp. Now in order to call euler.cpp functions from Python, we first need to create a interface file called euler.i with the following lines

%module euler
%{
       #include "euler.cpp"
%}
%include "euler.cpp"

The next thing to do is to generate the Python module euler.py by the following commands

$ swig -c++ -python euler.i
$ g++ -c -O3 -fPIC euler_wrap.cxx -I /usr/include/python2.6/
$ g++ -shared -O3 euler_wrap.o -o _euler.so

If there are no errors in your code or what you typed you should see euler.py in the directory. Run python and call your required function by
>>> import euler
>>> euler.requiredfunction()

No comments:

Post a Comment