Call C in Python

C: build a library

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

Python: load the library

1
2
3
from ctypes import *
libtest = cdll.LoadLibrary(libtest.so')
print libtest.func(arg_list)

Makefile sample and python sample code

c_void_p

For the types without need to know the detailed layout, we can just use c_void_p, especially when we cannot find the strictly matched self-defined type such as LP_cfloat_1024.

pointer, POINTER, byref

POINTER is used for defining type.

pointer and byref function similarly. However, pointer does a lot more work since it constructs a real pointer object, so it is faster to use byref if you don’t need the pointer object in Python itself.

memory issue:

write free function in C code

1
2
3
4
5
void freeme(char *ptr)
{
printf("freeing address: %p\n", ptr);
free(ptr);
}

call free function in Python

1
2
3
4
lib = cdll.LoadLibrary('./string.so')
lib.freeme.argtypes = c_void_p,
lib.freeme.restype = None
lib.freeme(ptr)