[Django]-How Can i integrate c++ and Python with SWIG

4👍

I often use swig for work in order to translate code to multiple languages and it is a really useful tool.

In order to understand what is the best way for you, you should observe your software interfaces. If you c++ classes have methods that only receive and returns simple types like strings or stl structures, you can be confident that your code doesn’t have problems being “swigged”. The problems come to you when you have complex interfaces.

An another issue with python is the presence of GIL that in multithreaded environments (with blocking calls in c++ side) can cause a lot of problems and involves in a complex management (using python-dev library in your c++ code).

A suggestion if your destination code is written only in python is to take a look of boost-python libraries that, being more specialized, are often more simple to use with python. The problems with multithreaded environments, however, remain.

6👍

Using swig is easy. Usually easier than people think.
See http://www.swig.org/tutorial.html.

Basically you just a have to write an interface file *.i that just includes the headers you need.
example.i :

 %module example
  %{
  /* Includes the header in the wrapper code */
  #include "header.h"
  %}

  /* Parse the header file to generate wrappers */
  %include "header.h"

Then use SWIG to generate a wrapper. Compile it with your c++ code and you’re done:

$ swig -python example.i
$ g++ -c example.cc example_wrap.cc \
    -I/usr/local/include/python2.1
$ ld -shared example.o example_wrap.o -o _example.so

You got your python module.

>>> import example
>>> example.foo()
👤log0

3👍

How to use SWIG to interface python and C++. (Tongue in cheek)

  • Generate a .i file that represents some C++ header. Even though SWIG parses (tries to parse) your header file, it still needs a swig interface file to tell swig what is to be imported.
  • Solution: Simple! Tell one of your project members to write a C++ header file parser that generates a .i file.
  • Next run swig against that .i file.
  • Then watch it fail.
  • Edit the header file and insert #ifndef SWIG … #endif around the code that SWIG doesn’t understand.
  • Rinse and repeat.
  • Once it works, watch your 50 line c++ header file balloon into a 5000+ line swig .cpp file, and a somewhat smaller .py file.
  • Do the same with all of the header files that you want to be wrapped.
  • Compile your new and improved C++ application with hooks callable by python.
  • Go to lunch. The compile and link won’t be done anytime soon.

Leave a comment