Sam Hooke

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!

Calling C from Python

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 liblife.so -fPIC liblife.c

3) Use Python ctypes to load library and execute.

life.py
import ctypes
import os

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

Running life.py 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 liblife.so

Further reading:

<< Previous: Building against `libusb`
Next: Hugo tag and category pages >>