Foreign Function Interface for Python calling C code.
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
C Foreign Function Interface for Python calling C code. CFFI provides a way to interface with C libraries from Python without requiring extensive knowledge of Python C extension development, offering both ABI (Application Binary Interface) and API modes for different use cases.
pip install cffiimport cffiMost common usage pattern:
from cffi import FFIfrom cffi import FFI
# Create FFI instance
ffi = FFI()
# Define C declarations
ffi.cdef("""
int printf(const char *format, ...);
""")
# Load C library
C = ffi.dlopen(None) # Load C standard library
# Call C function
C.printf(b"Hello, World!\n")
# Create C data structures
p = ffi.new("int *")
p[0] = 42
print(p[0]) # 42CFFI operates on a clear separation between declaration and implementation:
_cffi_backend C extension)Fundamental FFI functionality including instance creation, C code declaration parsing, and dynamic library loading. These operations form the foundation of all CFFI usage.
class FFI:
def __init__(self, backend=None): ...
def cdef(self, csource, override=False, packed=False, pack=None): ...
def dlopen(self, name, flags=0): ...
def dlclose(self, lib): ...
def verify(self, source='', tmpdir=None, **kwargs): ...C memory allocation, deallocation, garbage collection, and address operations. CFFI provides automatic memory management with options for custom allocators and manual control.
def new(self, cdecl, init=None): ...
def new_allocator(self, alloc=None, free=None, should_clear_after_alloc=True): ...
def cast(self, cdecl, source): ...
def addressof(self, cdata, *fields_or_indexes): ...
def gc(self, cdata, destructor, size=0): ...C type introspection and manipulation operations. The type system provides complete information about C types, sizes, alignment, and structure layouts.
def typeof(self, cdecl): ...
def sizeof(self, cdecl): ...
def alignof(self, cdecl): ...
def offsetof(self, cdecl, *fields_or_indexes): ...
def getctype(self, cdecl, replace_with=''): ...
def list_types(self): ...Converting between Python and C data representations. These functions handle string conversion, array unpacking, buffer operations, and memory transfers.
def string(self, cdata, maxlen=-1): ...
def unpack(self, cdata, length): ...
def from_buffer(self, cdecl, python_buffer, require_writable=False): ...
def memmove(self, dest, src, n): ...
buffer: callable # Buffer property for raw data accessCreating Python callbacks for C code and managing Python object handles in C. Essential for bidirectional communication between Python and C.
def callback(self, cdecl, python_callable=None, error=None, onerror=None): ...
def new_handle(self, x): ...
def from_handle(self, x): ...
def release(self, x): ...Advanced features for generating and compiling C extensions at runtime. These capabilities enable complex integration scenarios and performance optimization.
def set_source(self, module_name, source, source_extension='.c', **kwds): ...
def set_source_pkgconfig(self, module_name, pkgconfig_libs, source, source_extension='.c', **kwds): ...
def compile(self, tmpdir='.', verbose=0, target=None, debug=None): ...
def emit_c_code(self, filename): ...
def emit_python_code(self, filename): ...
def distutils_extension(self, tmpdir='build', verbose=True): ...Error management, system integration utilities, and platform-specific functionality including errno handling and Windows Unicode support.
# Error handling
errno: property # C errno access
def getwinerror(self, code=-1): ...
# Utilities
def include(self, ffi_to_include): ...
def set_unicode(self, enabled_flag): ...
def init_once(self, func, tag): ...
def embedding_api(self, csource, packed=False, pack=None): ...
def embedding_init_code(self, pysource): ...
def def_extern(self, *args, **kwds): ...class FFIError(Exception): ...
class CDefError(Exception): ...
class VerificationError(Exception): ...
class VerificationMissing(Exception): ...
class PkgConfigError(Exception): ...# Version information
__version__: str # "1.17.1"
__version_info__: tuple # (1, 17, 1)
# FFI instance attributes
NULL: CData # NULL pointer constant
CData: type # Base class for C data objects
CType: type # Base class for C type objectsffi = FFI()
ffi.cdef("int puts(const char *s);")
libc = ffi.dlopen(None) # System C library
libc.puts(b"Hello from C!")ffi = FFI()
ffi.cdef("""
struct point {
int x, y;
};
""")
# Create and use struct
p = ffi.new("struct point *")
p.x = 10
p.y = 20
print(f"Point: ({p.x}, {p.y})")ffi = FFI()
# Allocate array
arr = ffi.new("int[]", [1, 2, 3, 4, 5])
print(len(arr)) # 5
print(arr[2]) # 3
# Convert to Python list
py_list = ffi.unpack(arr, len(arr))
print(py_list) # [1, 2, 3, 4, 5]Install with Tessl CLI
npx tessl i tessl/pypi-cffi