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

core-ffi.mddocs/

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 patterns.

Capabilities

FFI Instance Creation

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

C Declaration Parsing

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

Dynamic Library Loading

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)

Library Closing

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

Code Verification and Compilation

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 8

Embedding API Declaration

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

Error Conditions

  • CDefError: Raised for invalid C syntax or declarations
  • OSError: Raised when library loading fails
  • VerificationError: Raised when verification/compilation fails
  • TypeError: Raised for invalid parameter types

Integration Patterns

Multiple Library Loading

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)

Declaration Override

ffi = FFI()
ffi.cdef("int func(int x);")

# Later override with more specific declaration
ffi.cdef("int func(int x, int y);", override=True)

Packed Structures

ffi = FFI()
ffi.cdef("""
    struct packed_data {
        char flag;
        int value;
        char data[100];
    };
""", packed=True)

# Structure fields are tightly packed without padding

Install with Tessl CLI

npx tessl i tessl/pypi-cffi

docs

callbacks-handles.md

core-ffi.md

data-conversion.md

error-handling.md

index.md

memory-management.md

source-generation.md

type-system.md

tile.json