Home | Articles | CV (pdf | short)
<2013-08-28> by Lorenzo

Python and C with ctypes

Calling C code from Python is very simple using ctypes. Here is a very simple example to get you started and to serve as a reminder for me!

Let's say you have this C file, defining 3 functions:

First, you want to compile this C file into a shared object. Here is a Makefile to do just this: simple type make all and you're done.

Finally, you can call these C functions from Python using ctypes:

Obviously, there is much more to it and things get more complicated soon, but, as you can see, for simple tasks like this using ctypes is pretty straitforward.