Structures and unions must derive from theStructure andUnionbase classes which are defined in thectypes module. Each subclassmust define a_fields_ attribute._fields_ must be a list of2-tuples, containing afield name and afield type.
The field type must be actypes type likec_int, or any otherderivedctypes type: structure, union, array, pointer.
Here is a simple example of a POINT structure, which contains twointegers namedx andy, and also shows how to initialize astructure in the constructor:
>>> from ctypes import *>>> class POINT(Structure):... _fields_ = [("x", c_int),... ("y", c_int)]...>>> point = POINT(10, 20)>>> print point.x, point.y10 20>>> point = POINT(y=5)>>> print point.x, point.y0 5>>> POINT(1, 2, 3)Traceback (most recent call last): File "<stdin>", line 1, in ?ValueError: too many initializers>>>You can, however, build much more complicated structures. Structurescan itself contain other structures by using a structure as a fieldtype.
Here is a RECT structure which contains two POINTs namedupperleftandlowerright
>>> class RECT(Structure):... _fields_ = [("upperleft", POINT),... ("lowerright", POINT)]...>>> rc = RECT(point)>>> print rc.upperleft.x, rc.upperleft.y0 5>>> print rc.lowerright.x, rc.lowerright.y0 0>>>Nested structures can also be initialized in the constructor inseveral ways:
>>> r = RECT(POINT(1, 2), POINT(3, 4))>>> r = RECT((1, 2), (3, 4))
Fields descriptors can be retrieved from theclass, they are usefulfor debugging because they can provide useful information:
>>> print POINT.x<Field type=c_long, ofs=0, size=4>>>> print POINT.y<Field type=c_long, ofs=4, size=4>>>>