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 §
- Write the C library.
int life(void);
int life()
{
return 42;
}- Compile.
gcc -shared -o liblife.so -fPIC liblife.c
- Use Python
ctypesto load library and execute.
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:
- Compile the code with the Position Independent Code Flag, generating
testlib.o:
gcc -c -fPIC liblife.c -o liblife.o
- Generated a shared object file from the object file:
gcc liblife.o -shared -o liblife.so
Further reading §
- Use
-sonameoption (and example). - More compilation details.
- Ensure shared object is 32-bit or 64-bit as appropriate.
- Passing more complex data types such as arrays.
Alternatives §
- cffi is another Python library, which prefers working at the API level, in contrast to ctypes which works at the ABI level.
- SWIG is written in C/C++, and supports interfacing between C/C++ and a variety of high-level languages, including Python. It requires writing a SWIG interface file.
- Cython.
- pybind11 (for C++11).