Python Glossary Русский

all Python 3ctypesterm

ctypes.Structure

structures

The base class for describing a C struct: fields are declared in a _fields_ list of (name, ctypes type) pairs.

Syntax

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

Field order and types must match the C definition exactly, or the data is read shifted without any error. Fields are aligned the way the C compiler aligns them, so sizeof may exceed the sum of field sizes; _pack_ changes that. For reading and writing binary formats without calling C code the struct module is simpler.

Examples

import ctypes
class Point(ctypes.Structure):
    _fields_ = [('x', ctypes.c_int), ('y', ctypes.c_int)]
p = Point(1, 2)
print(p.x, p.y)   # → 1 2
p.x = 10
print(p.x)   # → 10
print(ctypes.sizeof(Point))   # → ? обычно 8 байт — два int по 4

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy