Foreign Function Interface for Python calling C code.
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Fundamental FFI functionality including instance creation, C code declaration parsing, and dynamic library loading. These operations form the foundation of all CFFI usage patterns.
Creates a new FFI instance that manages C declarations, type system, and backend operations.
class FFI:
def __init__(self, backend=None):
"""
Create an FFI instance.
Parameters:
- backend: Optional backend override (mostly for testing)
Returns:
FFI instance with initialized parser and type system
"""Parses C source code declarations and registers functions, types, and global variables for later use.
def cdef(self, csource, override=False, packed=False, pack=None):
"""
Parse the given C source declarations.
Parameters:
- csource (str): C source code containing declarations
- override (bool): Allow overriding existing declarations
- packed (bool): Pack all structs without field alignment
- pack (int): Maximum alignment for struct fields
Returns:
None (modifies FFI instance state)
"""Usage Example:
ffi = FFI()
ffi.cdef("""
// Function declarations
int printf(const char *format, ...);
void *malloc(size_t size);
void free(void *ptr);
// Structure definitions
struct point {
int x, y;
};
// Type definitions
typedef struct point point_t;
// Constants and enums
enum color { RED, GREEN, BLUE };
// Global variables
extern int errno;
""")Loads dynamic libraries and makes their symbols available through the declared C interface.
def dlopen(self, name, flags=0):
"""
Load and return a dynamic library.
Parameters:
- name (str|None): Library name/path, or None for standard C library
- flags (int): Loading flags (platform-specific)
Returns:
Library object with access to declared functions and variables
"""Usage Examples:
# Load standard C library
libc = ffi.dlopen(None)
libc.printf(b"Hello, World!\n")
# Load specific library
libm = ffi.dlopen("libm.so.6") # Linux
# libm = ffi.dlopen("msvcrt.dll") # Windows
# Access library functions
result = libm.sin(3.14159 / 2)Closes a previously opened dynamic library and invalidates access to its symbols.
def dlclose(self, lib):
"""
Close a library obtained with ffi.dlopen().
Parameters:
- lib: Library object returned by dlopen()
Returns:
None
Warning: Access to functions/variables after closing may cause segfaults
"""Verifies that C declarations compile correctly and returns a compiled library object with C-level API compatibility.
def verify(self, source='', tmpdir=None, **kwargs):
"""
Verify declarations compile and return dynamic library.
Parameters:
- source (str): Additional C source code for compilation
- tmpdir (str): Temporary directory for compilation files
- **kwargs: Additional compilation options
Returns:
Compiled library object with declared interface
"""Usage Example:
ffi = FFI()
ffi.cdef("""
int add(int a, int b);
""")
lib = ffi.verify("""
int add(int a, int b) {
return a + b;
}
""")
result = lib.add(5, 3) # Returns 8Declares functions for embedding Python in C applications.
def embedding_api(self, csource, packed=False, pack=None):
"""
Declare embedding API for Python-in-C integration.
Parameters:
- csource (str): C source code with function declarations
- packed (bool): Pack structs without alignment
- pack (int): Maximum struct alignment
Returns:
None (enables embedding mode)
"""ffi = FFI()
ffi.cdef("""
// Math functions
double sin(double x);
double cos(double x);
// String functions
char *strcpy(char *dest, const char *src);
int strcmp(const char *s1, const char *s2);
""")
# Load multiple libraries
libm = ffi.dlopen("libm.so.6")
libc = ffi.dlopen(None)
# Use functions from different libraries
angle = libm.sin(3.14159 / 4)
libc.printf(b"sin(π/4) = %f\n", angle)ffi = FFI()
ffi.cdef("int func(int x);")
# Later override with more specific declaration
ffi.cdef("int func(int x, int y);", override=True)ffi = FFI()
ffi.cdef("""
struct packed_data {
char flag;
int value;
char data[100];
};
""", packed=True)
# Structure fields are tightly packed without paddingInstall with Tessl CLI
npx tessl i tessl/pypi-cffi