Feb 11, 2012

Swig Tutorial example Mac Os Lion

This tutorial is based on Leopard Tutorial but still works, thou some warnings.

First, we create an example.c file with this content:

/* File : example.c */

#include <time.h>
double My_variable = 10.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);
}

Second, we create the interface between C and Python with the following file:

/* 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();

Now that we have all the source files we need, we compile them in this way:

$ swig -python example.i
$ cc -c `python-config --cflags` example.c example_wrap.c
$ cc -bundle `python-config --ldflags` example.o example_wrap.o -o _example.so

if you have problems with this step check this other post

So, everything looks nice, but how do we use the dynamic module in python?

>>> import example
>>> example
<module 'example' from 'example.pyc'>
>>> example.cvar.My_variable
10.0
>>> example.my_mod(20,10)
0
>>> example.fact(14)
1278945280
>>> example.get_time()
'Sat Feb 11 19:27:05 2012\n'

disclaimer: this is just the tutorial from the swig's homepage, it only shows how you can actually use some C power into python. For example, scipy package, in the module cluster uses a C function wrapped into python code.

2 comments:

Anonymous said...

Thanks for the mac gcc arguments for the swig tutorial. I'm new to using gcc on mac so the mac-specific usage threw me.

carpincho said...

Great!
Thank for the comment! :)