Sam Hooke

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.

Simple example §

  1. Write the C library.
liblife.c
int life(void);

int life()
{
    return 42;
}
  1. Compile.
gcc -shared -o liblife.so -fPIC liblife.c
  1. 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.

Step 2 in detail §

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

  1. Compile the code with the Position Independent Code Flag, generating testlib.o:
gcc -c -fPIC liblife.c -o liblife.o
  1. Generated a shared object file from the object file:
gcc liblife.o -shared -o liblife.so

Further reading §

Alternatives §