Sunday, January 31, 2010

ctypes : Loading simple C library in Python 2.5+

Just discovered this when I was glancing through the pystream (a CUDA library for Python) source codes.

In Python2.5+, it is possible to directly load simple C shared libraries from Python without the need for writing C wrappers for it. (SWIG or manually writing one). This can be achieved using the Python ctypes module.

Lets take a simple example:


/* test.c */
int multiply(int a,int b){
return a * b;
}


Compile it as a SO library (ref: Writing and using shared libraries):


gcc -c -fPIC test.c
gcc -shared -fPIC -o libtest.so test.o


Now we got an SO file with a test function, lets load it in Python


In [1]: import ctypes

In [2]: libtest = ctypes.cdll.LoadLibrary('/path/to/libtest.so')

In [3]: libtest.multiply(30,99)
Out[3]: 2970


Hope this would be useful to someone.

More details : http://docs.python.org/library/ctypes.html

Happy Hacking :D
Post a Comment