SWIG for Python C Binding

July 8, 2019


There are so many ways to do Python-C bindings, but my favorite is always SWIG. It allows very easy binding with minimum additional codes.

Suppose now I have example.c:

And example.h:

I can just add one single file example.i:

After that I use the following command to compile all the codes:

$ swig -python example.i

$ gcc -c example.c example_wrap.c -fPIC -I/usr/include/python3.6

$ ld -shared example.o example_wrap.o -o _example.so

Now I am able to run the following code in Python 3 and see the expected output.