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
¶
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)
Convenience Function¶
header_to_ctypes
¶
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'
|
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
¶
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