ctypes gives Python a direct route into functions that were compiled from C and packaged as a dynamic library. That can be useful when an algorithm needs more speed, or when a useful function already exists in a shared library and you want to call it from Python without rewriting it. A small multiplication routine is enough to show the mechanics.

int
multiply(int num1, int num2)
{
    return num1 * num2;
}

If you are building on Windows, the file also needs an entry point and an explicit export, so the version may look like this:


#include <windows.h>


BOOL APIENTRY
DllMain(HANDLE hModule, DWORD dwReason, LPVOID lpReserved)
{
    return TRUE;
}

__declspec(dllexport) int
multiply(int num1, int num2)
{
    return num1 * num2;
}

Next, turn the C source into a dynamic library. On Linux:


gcc -c -fPIC libtest.c
gcc -shared libtest.o -o libtest.so

On Windows:


cl -LD libtest.c -libtest.dll

With the library built, Python can load it and call multiply. On Windows, change libtest.so to libtest.dll:


>>> from ctypes import *
>>> import os
>>> libtest = cdll.LoadLibrary(os.getcwd() + '/libtest.so')
>>> print libtest.multiply(2, 2)
4

The library needs to be in the current working directory, since the example builds its path from os.getcwd().