Skip to content

ctypes Writer

The ctypes writer generates Python source code that uses the ctypes standard library to define C type bindings. The output is a runnable Python module containing struct/union classes, enum constants, type aliases, callback types, and function prototype annotations.

Writer Class

CtypesWriter

CtypesWriter(lib_name='_lib')

Writer that generates Python ctypes binding modules from headerkit IR.

Options

lib_name : str Variable name for the loaded library object. Defaults to "_lib". Controls the variable name used in function prototype annotations (e.g., _lib.func.argtypes = [...]).

Example

::

from headerkit.writers import get_writer

writer = get_writer("ctypes", lib_name="mylib")
source = writer.write(header)

# Or directly:
from headerkit.writers.ctypes import CtypesWriter
writer = CtypesWriter(lib_name="_lib")
source = writer.write(header)

write

write(header)

Convert header IR to Python ctypes binding source code.

hash_comment_format

hash_comment_format()

Return format string for wrapping TOML cache metadata in Python comments.

Convenience Function

header_to_ctypes

header_to_ctypes(header, lib_name='_lib')

Convert all declarations in a Header to a Python ctypes module string.

Parameters:

Name Type Description Default
header Header

Parsed header IR from headerkit.

required
lib_name str

Variable name for the loaded library object. Used in function prototype annotations (e.g., _lib.func.argtypes = [...]).

'_lib'

Returns:

Type Description
str

A string of Python source code defining ctypes bindings.

Low-Level Functions

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

type_to_ctypes

type_to_ctypes(t)

Convert a type expression to its ctypes string representation.

Handles special cases like const char * -> ctypes.c_char_p, void * -> ctypes.c_void_p, and pointer/array composition.

Example

from headerkit.backends import get_backend
from headerkit.writers import get_writer

backend = get_backend()
header = backend.parse("""
typedef struct {
    int x;
    int y;
} Point;

int distance(Point* a, Point* b);
""", "geometry.h")

writer = get_writer("ctypes", lib_name="_geometry")
print(writer.write(header))

Output:

"""ctypes bindings generated from geometry.h."""

import ctypes
import ctypes.util
import sys

# ============================================================
# Structures and Unions
# ============================================================

class Point(ctypes.Structure):
    _fields_ = [
        ("x", ctypes.c_int),
        ("y", ctypes.c_int),
    ]

# ============================================================
# Function Prototypes
# ============================================================

_geometry.distance.argtypes = [ctypes.POINTER(Point), ctypes.POINTER(Point)]
_geometry.distance.restype = ctypes.c_int