[SWIG] How to add C function in Python by using SWIG

Here is a simple example to use SWIG to automatically wrap C function and generate a wrapper and build a shared library for python.

/*** File : example.c ***/
#include 
<time.h>
double My_variable = 3.0;
int fact(int n) {
if (n <= 1) return 1;
else return n*fact(n-1);
}
int my_mod(int x, int y) {
return (x%y);
}
char *get_time()
{
time_t ltime;
time(&ltime);
return ctime(&ltime);
}
/*************************/


/*** example.i ***/
%module example
%{
/* Put header files here or function declarations like below */
extern double My_variable;
extern int fact(int n);
extern int my_mod(int x, int y);
extern char *get_time();
%}
extern double My_variable;
extern int fact(int n);
extern int my_mod(int x, int y);
extern char *get_time();
/******************/


Steps:
1. $> swig -python example.i
2. $ >gcc -c -fpic example.c example_wrap.c -I/usr/include/python2.7 -I/usr/lib/python2.7/config
3. $> ld -shared example.o example_wrap.o -o _example.so
4. $> python
>>>import example
>>>example.fact(5)
120 -> Oh, yes!

Here is another example:

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()


What if you have some pointer arguments in C ? How to deal with it in Python? 

For example:
void add(double a, double b, double *result) {
 *result = a + b;
}

Please refer to this document. It will give you the nametype mapping in SWIG.
http://www.swig.org/Doc1.3/Arguments.html




Comments

Popular posts from this blog

[Open vSwitch] How to get port statistics from interface in OVS

[Quagga] How to compile and install Quagga on Ubuntu 12.04

[JSON] How to use jansson lib to generate JSON data in C