old blog,

ctypes : Loading simple C library in Python 2.5+

Izhar Firdaus Izhar Firdaus Follow Support Jan 31, 2010 · 1 min read
ctypes : Loading simple C library in Python 2.5+
Creative Commons License
This work is licensed under a Creative Commons Attribution 4.0 International License.
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
Written by Izhar Firdaus Follow Support
I'm a system architect, data engineer and developer advocate with passion in Free / Open Source software, entrepreneurship, community building, education and martial art. I take enjoyment in bridging and bringing together different FOSS technologies to help businesses and organizations utilize IT infrastructure to aid and optimize their business and organizational process.

The Deen Show : Proper Name for GOD

Video which describes etymology of Allah & Eloh, and the proper word to use to describe GOD - from the Deen Show. Guest - Yusuf E...

In old blog, Jan 08, 2010

« Previous Post

Event Report : IIUM FOSSDay 2010

Event date: 19th Feb 2010Location: International Islamic University Malaysia (IIUM)(I know, I tend to be lazy to write reports, anywa...

In old blog, Feb 27, 2010

Next Post »