Using SWIG to expose C code to Python

Sergey Fomel left a valuable comment on my post about computing the error function erf(x). He gave some sample code for exposing C functions to Python via SWIG on Linux. I haven’t used SWIG, but I’ve heard good things about it. I believe Google uses SWIG extensively to make C++ code callable from Python.

Here’s Sergey’s code.

bash$ cat erf.i

%module erf
double erf(double);

bash$ swig -o erf_wrap.c -python erf.i
bash$ gcc -o erf_wrap.os -c -fPIC -I/usr/include/python2.4 erf_wrap.c
bash$ gcc -o -shared erf_wrap.os
bash$ python
>>> from erf import erf
>>> erf(1)

One thought on “Using SWIG to expose C code to Python

Leave a Reply

Your email address will not be published. Required fields are marked *