0Pricing
Python Academy · Lesson

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))   # 42

All lessons in this course

  1. Why C Extensions? Use Cases and Trade-offs
  2. ctypes: Calling C Libraries from Python
  3. cffi: C Foreign Function Interface
  4. Writing a Python C Extension Module
← Back to Python Academy