@@ -3161,6 +3161,72 @@ fields, or any other data types containing pointer type fields.
31613161 that should be merged into a containing structure or union.
31623162
31633163
3164+ .. decorator :: struct(*, align=None, layout, endian='native', pack=None)
3165+ :module: ctypes.util
3166+
3167+ A :term: `decorator ` that allows generating structure types using an
3168+ annotation-based syntax, similar to the :mod: `dataclasses ` module.
3169+
3170+ For example:
3171+
3172+ .. code-block :: python
3173+
3174+ from ctypes.util import struct
3175+ from ctypes import c_int
3176+
3177+ @struct
3178+ class Point :
3179+ x: c_int
3180+ y: c_int
3181+
3182+ point = Point(1 , 2 )
3183+
3184+ *align *, *layout *, and *pack * supply the value for the :attr: `~ctypes.Structure._align_ `,
3185+ :attr: `~ctypes.Structure._layout_ `, and :attr: `~ctypes.Structure._pack_ `
3186+ attributes, respectively.
3187+
3188+ *endian * controls which structure class will be used as the base.
3189+
3190+ - If *endian * is ``'native' ``, :class: `~ctypes.Structure ` will be used.
3191+ - If *endian * is ``'big' ``, :class: `~ctypes.BigEndianStructure ` will be used.
3192+ - If *endian * is ``'little' ``, :class: `~ctypes.LittleEndianStructure ` will be used.
3193+
3194+ Any other value will raise a :class: `ValueError `.
3195+
3196+ For controlling field-specific data, wrap the annotation in :class: `typing.Annotated `
3197+ with :class: `CFieldInfo ` as the second argument, like so:
3198+
3199+ .. code-block :: python
3200+
3201+ @struct
3202+ class PyObject :
3203+ ob_refcnt: c_ssize_t
3204+ ob_type: c_void_p
3205+
3206+ @struct
3207+ class PyHovercraftObject :
3208+ ob_base: Annotated[PyObject, CFieldInfo(anonymous = True )]
3209+
3210+ .. versionadded :: next
3211+
3212+
3213+ .. class :: CFieldInfo(anonymous=False, bit_width=None)
3214+ :module: ctypes.util
3215+
3216+ Information regarding a structure field defined by the :func: `struct `
3217+ decorator. This should be used in the second argument of a
3218+ :class: `typing.Annotated ` wrapping a ctypes type.
3219+
3220+ *anonymous * specifies whether the field will be present in the
3221+ :attr: `~Structure._anonymous_ ` attribute of the generated class.
3222+
3223+ If *bit_width * is non-``None ``, the annotated field will be *bit_width *
3224+ number of bits in the generated structure. This is equivalent to passing
3225+ a third item in :attr: `~ctypes.Structure._fields_ `.
3226+
3227+ .. versionadded :: next
3228+
3229+
31643230.. _ctypes-arrays-pointers :
31653231
31663232Arrays and pointers
0 commit comments