Structures and unions
User defined types are created by decorating a class that stores the
corresponding member annotations. Each of the types, struct and
union, has its own decorator function, @cstruct and
@cunion, respectively.
- @cstruct(cls=None, /, *, alias=None, wrapped=True)[source]
Class decorator that returns a C struct class that inherits from
ctypes.Structure. The decorated class must annotate the struct members with valid types.<name> : <type>
The
typefield takes all types from the basic types section, plus all pointer and array types derived from them. User defined types are also valid, together with ctypes types.import fancytypes as ft # 128-bit complex number as defined by the C99 standard @ft.cstruct class complex128: real : ft.real64 # Real part imag : ft.real64 # Imaginary part # Sample struct that can store an N-dimensional array @ft.cstruct class ndarray: data : ft.pointer(ft.real64) # Pointer to the first data array element dim : ft.pointer(ft.int32) # Pointer to the first dimension array element ndim : ft.int32 # Number of dimensions
- Parameters:
alias (str, optional) – User defined alias for the type, default is an explicit list with the fields
wrapped (bool, optional) – Flag to wrap the type or return a
ctypesclass, default isTrue
- @cunion(cls=None, /, *, alias=None, wrapped=True)[source]
Class decorator that returns a C union class that inherits from
ctypes.Union. Union members are annotated following the same rules described in@cstruct.- Parameters:
alias (str, optional) – User defined alias for the type, default is an explicit list with the fields
wrapped (bool, optional) – Flag to wrap the type or return a
ctypesclass, default isTrue
Structure and union types with wrapped=True have a corresponding
numpy.dtype and can be used as a datatype in NumPy arrays. Pointer
types are first converted to ctypes.c_void_p, which NumPy interprets as
unsigned integers. This conversion does not affect the actual structure or
union type.