cffi: C Foreign Function Interface
Use cffi for more Pythonic C interop with inline C declarations.
What Is cffi?
cffi (C Foreign Function Interface) lets you call C code from Python using C declarations rather than ctypes classes. It is more Pythonic and often safer.
# pip install cffi
from cffi import FFI
ffi = FFI()
ffi.cdef("double sqrt(double x);")
libm = ffi.dlopen(None) # current process
print(libm.sqrt(2.0)) # 1.4142...ABI vs API Mode
ffi.dlopen() is ABI mode — calls an existing shared library at runtime. API mode compiles a C wrapper and is faster and more robust.
from cffi import FFI
ffi = FFI()
# ABI mode (no compile step):
ffi.cdef("int abs(int x);")
libc = ffi.dlopen("libc.so.6") # Linux
print(libc.abs(-42)) # 42All lessons in this course
- Why C Extensions? Use Cases and Trade-offs
- ctypes: Calling C Libraries from Python
- cffi: C Foreign Function Interface
- Writing a Python C Extension Module