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


Izad Che Muda said…
Dude, I know it's off topic, but what do you know about Groovy language? It's not as old school as Java and more Pyton/Ruby-like. I think I might learn it. Well it's either Groovy or Python. What do you think?
Unknown said…
dont know much .. but imo, Python is much simpler and straightforward than Groovy ..

just try both and see which you like more and serve the purpose which you are trying to achieve better ..
王同 said…
Interesting! Thanks :)

Popular posts from this blog

Announcing PlatoCDP, a Plone distribution for enterprises.

Adding simple popup to Plone frontpage

An Open Letter for the Rector of PETRONAS University of Technology