CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-cffi

Foreign Function Interface for Python calling C code.

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

CFFI

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.

Package Information

  • Package Name: cffi
  • Language: Python
  • Installation: pip install cffi

Core Imports

import cffi

Most common usage pattern:

from cffi import FFI

Basic Usage

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

Architecture

CFFI operates on a clear separation between declaration and implementation:

  • FFI Instance: Main interface managing C declarations, type system, and backend
  • C Definitions: Parsed C declarations stored in the FFI instance
  • Dynamic Libraries: Loaded C libraries providing actual function implementations
  • Type System: Complete C type representation with Python bindings
  • Memory Management: Automatic garbage collection with manual control options
  • Backend: Pluggable backend system (default: _cffi_backend C extension)

Capabilities

Core FFI Operations

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): ...

Core FFI Operations

Memory Management

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): ...

Memory Management

Type System

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): ...

Type System

Data Conversion

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 access

Data Conversion

Callbacks and Handles

Creating 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): ...

Callbacks and Handles

Source Generation and Compilation

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): ...

Source Generation

Error Handling and Utilities

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): ...

Error Handling

Exception Classes

class FFIError(Exception): ...
class CDefError(Exception): ...
class VerificationError(Exception): ...
class VerificationMissing(Exception): ...
class PkgConfigError(Exception): ...

Constants and Attributes

# 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 objects

Common Patterns

Loading System Libraries

ffi = FFI()
ffi.cdef("int puts(const char *s);")
libc = ffi.dlopen(None)  # System C library
libc.puts(b"Hello from C!")

Working with Structures

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})")

Memory Management with Arrays

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
Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/cffi@1.17.x
Publish Source
CLI
Badge
tessl/pypi-cffi badge