Shared Objects in Python

ctypes is a foreign function library for Python. It provides C compatible data types, and allows calling functions in DLLs or shared libraries. It can be used to wrap these libraries in pure Python.

Eine Einfache Library

First let us write a small c-library, a simple Hello-World example is sufficient:

#include <stdio.h>

void myprint(void);

void myprint()
{
    printf("Hello World\n");
}

Now, compile it as a shared library:

$ gcc -shared -Wl,-soname,testlib -o testlib.so -fPIC testlib.c

Zugriff auf Shared Objects

In Python, write a wrapper using ctypes:

import ctypes

testlib = ctypes.CDLL("testlib.so")
testlib.myprint()

and execute it like this:

$ python cwrapper.py

You should see the following output:

% python cwrapper.py
Hello World