ctypes & CFFI: Calling Native C Libraries (.dll / .so)
1Concept
`ctypes` is Python's standard Foreign Function Interface (FFI). It loads shared C dynamic libraries (`.so`, `.dll`), declares C parameter types (`argtypes`), and invokes native functions directly.
2Architecture Diagram
Python Script ---> ctypes.CDLL("libc.so.6") ---> Direct native C execution on CPU3Code Example
Python 3.12
import ctypes
# Access standard C library via ctypes
libc = ctypes.CDLL(None) if hasattr(ctypes, "CDLL") and not sys.platform.startswith("win") else None
print("=== ctypes Foreign Function Interface (FFI) ===")
print("1. Load library: lib = ctypes.CDLL('libruntime.so')")
print("2. Set arg types: lib.compute.argtypes = [ctypes.c_int, ctypes.c_int]")
print("3. Set res type: lib.compute.restype = ctypes.c_int")
print("4. Direct Call: result = lib.compute(10, 20)")4Expected Output
=== ctypes Foreign Function Interface (FFI) ===
1. Load library: lib = ctypes.CDLL('libruntime.so')
2. Set arg types: lib.compute.argtypes = [ctypes.c_int, ctypes.c_int]
3. Set res type: lib.compute.restype = ctypes.c_int
4. Direct Call: result = lib.compute(10, 20)5Key Takeaways
- ✓CFFI is the modern, faster alternative to ctypes with better compiler integration.
- ✓Passing invalid pointers in ctypes can crash the Python process with Segmentation Fault (`SIGSEGV`).
- ✓Ideal for integrating legacy enterprise C/C++ libraries into Python backends.