Sam Hooke

Calling C from Python

Update 2020-04-11: Would recommend cffi over ctypes.

ctypes is Python library for calling C code from Python. Following is a very simple example of how to build a shared object (*.so file) from C code which can be called from Python using ctypes.

1) Write the C library.

liblife.c §
int life(void);

int life()
    return 42;

2) Compile.

gcc -shared -o -fPIC liblife.c

3) Use Python ctypes to load library and execute. §
import ctypes
import os

here = os.path.dirname(os.path.abspath(__file__))
libc = ctypes.cdll.LoadLibrary(os.path.join(here, ""))

Running will echo 42 to stdout.

Further details

To expand upon step 2), it is actually the following two steps combined:

2a) Compile the code with the Position Independent Code Flag, generating testlib.o:

gcc -c -fPIC liblife.c -o liblife.o

2b) Generated a shared object file from the object file:

gcc liblife.o -shared -o

Further reading:

These are rough notes from whatever I was working on, interested in or thinking about at the time. They vary greatly in quality and length, but prove useful to me, and hopefully to you too!

← Previous: Building against `libusb`
Next: Hugo tag and category pages →