Using SWIG to make python modules from C++ using the Vector library

Sometimes we need fast computing from a low level language such as C++ while maintaining the usability of a language like Python which makes data visualisation easier.  To make this work it is possible to wrap C++ so that it becomes a shared library that can be imported to python.

This is particularly useful with Vectors, a C++ library that can be a little nicer to use than the standard arrays.

I'll give an example of the steps below.

Start with your function that you want to be usable in python. 


#include <vector>
#include <iostream>
std::vector<int> testfunction(std::vector <int>& value){
  std::cout <<"Running\n";
  return value;

Here we've made a very simple vector function. It's only purpose is to tell us that it is running. We need a header file for the function


#ifndef TEST_H_
#define TEST_H_
#include <vector>
#include <iostream>

std::vector<int> testfunction(std::vector <int>& value);


Now we have our function let's make ourselves an input file for SWIG. This will tell it what functions we are using and how to cast them for Python.


%module example
#include "example.h"

%include "std_vector.i"
// Instantiate templates used by example
namespace std {
   %template(IntVector) vector<int>;

// Include the header file with above prototypes
%include "example.h"

The structure of this file is important. Firstly the %module example gives the title that we will eventually use for our python module. We must include the header file we made and the std_vector.i library for SWIG so that it understands vectors. We then give SWIG a template which will let it understand what vector we are passing it. (Google around to find out more about these template functions and which ones might be right for your code, SWIG has great documentation.)

Finally we include example.h for SWIG itself.

Now we can run all this, here are the compile functions for this example:


 swig -c++ -python example.i

 gcc -fpic -c example.cpp example_wrap.cxx -I /opt/ioa/software/python/2.7.8/include/python2.7
 gcc -Wl,--gc-sections -fPIC -shared -lstdc++ example.o example_wrap.o -o

We've got our shared library and our module All we have to do is call it in python!

>>> import example as e
>>> x=e.IntVector(5)
>>> e.testfunction(x)