Dec 2, 2012

Calling C functions from Python

Python is capable of calling functions from a C library. Say, we have the following C code which needs to be used in a python script. I'm using Ubuntu 12.04 with python 2.7.
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 the shared library has to be copied to /lib/x86_64-linux-gnu/
$ sudo cp c_code.so /lib/x86_64-linux-gnu/
The following python script imports the shared library and invokes functions from it.
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))

No comments:

Post a Comment