CFFI — C Foreign Function Interface for Python

2.0.0 · active · verified Sat Mar 28

CFFI (C Foreign Function Interface) lets Python code call C libraries by declaring C-like function signatures and types that can often be copy-pasted directly from header files. It supports four modes: ABI/API level each with inline or out-of-line (pre-compiled) preparation. The current stable release is 2.0.0 (released September 2025), requiring Python >=3.9. It is the recommended way to interface with C on PyPy and is used as a foundation by cryptography, bcrypt, and many other major Python packages.

Warnings

Install

Imports

Quickstart

Inline ABI mode: declare a C function signature and call it via dlopen. No C compiler needed, but prefer out-of-line API mode for production.

from cffi import FFI

ffi = FFI()

# Declare the C function signature (copy-paste from man page / header)
ffi.cdef("""
    size_t strlen(const char *s);
""")

# ABI mode: open the C standard library
C = ffi.dlopen(None)  # None = current process / libc on POSIX
                      # On Windows use ffi.dlopen('msvcrt') instead

# char* arguments must be bytes, not str
result = C.strlen(b"hello, cffi")
print(result)  # 11

# Allocate a C buffer
buf = ffi.new("char[]", b"world")
print(ffi.string(buf))  # b'world'

view raw JSON →