Skip to content

CFFI Writer

The CFFI writer generates C declaration strings suitable for passing to ffibuilder.cdef(). It handles structs, unions, enums, functions, typedefs, variables, and integer constants.

Writer Class

CffiWriter

CffiWriter(exclude_patterns=None, define_patterns=None, extra_cdef=None, module_var=None, extern_python=None)

Bases: BaseWriter

Writer that generates CFFI cdef strings from headerkit IR.

Options

exclude_patterns : list[str] | None Regex patterns. Declarations with names matching any pattern are excluded from output. define_patterns : Sequence[str] | None Regex patterns matched against Constant declaration names in the IR. Matching macro constants not already emitted as integer literals are appended as #define NAME ... lines (CFFI's verify-time syntax). extra_cdef : list[str] | None Arbitrary cdef lines appended verbatim after all generated output. module_var : str | None When set (e.g. "CDEF"), wraps the output as a valid Python module exporting <module_var>: str = ... and __all__ = [<module_var>]. extern_python : Sequence[str] | None Symbol names of Function or function-pointer Typedef declarations in Header.declarations to emit as extern "Python" callbacks.

write

write(header)

Convert header IR to CFFI cdef string, Python module, or reconciled script.

write_reconciled

write_reconciled(unit)

Render a ReconciledUnit containing common declarations and platform-guarded cdef blocks.

hash_comment_format

hash_comment_format()

Return format string for wrapping cache metadata in comments.

Convenience Function

header_to_cffi

header_to_cffi(header, exclude_patterns=None, extern_python_names=None)

Convert all declarations in a Header to a CFFI cdef string.

Parameters:

Name Type Description Default
header Header

Parsed header IR from headerkit.

required
exclude_patterns list[str] | None

List of regex patterns. Declarations with names matching any pattern will be excluded.

None
extern_python_names set[str] | None

Optional set of Function symbol names that will be emitted as extern "Python" declarations instead of plain C function declarations.

None

Returns:

Type Description
str

A string suitable for passing to ffibuilder.cdef().

Low-Level Functions

These functions are used internally by header_to_cffi and can be useful when working with individual declarations or type expressions.

type_to_cffi

type_to_cffi(t, tag_kinds=None)

Convert a type expression to its CFFI string representation.

decl_to_cffi

decl_to_cffi(decl, exclude_patterns=None, tag_kinds=None)

Convert a single IR declaration to a CFFI cdef string.

Returns None if the declaration should be excluded.