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.so 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 c_code.so /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 = "c_code.so"
dll = cdll.LoadLibrary(lib)
add = (lambda x,y: dll.add(c_int(x), c_int(y)))
print(add(1,1))
print(add(2,3))