Calling C functions in Python scripts

Jan 19, 2016

Python is an extensible language. Code written in compiled languages like C can be invoked from Python with a little effort. This allows software developers to write simple human readable scripts in Python to make use of faster libraries written in compiled languages.

Say, we have the following C code which needs to be used in a python script.

int add(int a, int b) 
    return (a+b) ; 

First, the C code has to be compiled as a shared library.

$ gcc -fpic -c c_code.c
$ gcc -shared -o c_code.o

Then, in linux, the shared library has to be copied to /usr/lib/. In linux OS this folder is designated to hold pre compiled libraries. You can either create a soft link in the /usr/lib folder.

$ sudo cp /lib/x86_64-linux-gnu/

Now we can start writing Python scripts to make use of the new library. Below is an example.

from ctypes import cdll,c_int
lib = ""
dll = cdll.LoadLibrary(lib)
add = (lambda x,y: dll.add(c_int(x), c_int(y)))