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.
- Compile.
- Use Python
ctypes
to load library and execute.
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
:
- Generated a shared object file from the object file:
Further reading §
- Use
-soname
option (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).