Pelokalan
Python ID
id en
Masuk
Proyek
library__ctypes.po Berkas proyek · python-docs-id-3.14 · Bahasa Indonesia
Modul PO Hanya lihat
Teks sumber — English
Terjemahan — Bahasa Indonesia
Structures and unions must derive from the :class:`Structure` and :class:`Union` base classes which are defined in the :mod:`!ctypes` module. Each subclass must define a :attr:`~Structure._fields_` attribute. :attr:`!_fields_` must be a list of *2-tuples*, containing a *field name* and a *field type*.
The field type must be a :mod:`!ctypes` type like :class:`c_int`, or any other derived :mod:`!ctypes` type: structure, union, array, pointer.
>>> from ctypes import * >>> class POINT(Structure): ... _fields_ = [("x", c_int), ... ("y", c_int)] ... >>> point = POINT(10, 20) >>> print(point.x, point.y) 10 20 >>> point = POINT(y=5) >>> print(point.x, point.y) 0 5 >>> POINT(1, 2, 3) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: too many initializers >>>
You can, however, build much more complicated structures. A structure can itself contain other structures by using a structure as a field type.
>>> class RECT(Structure): ... _fields_ = [("upperleft", POINT), ... ("lowerright", POINT)] ... >>> rc = RECT(point) >>> print(rc.upperleft.x, rc.upperleft.y) 0 5 >>> print(rc.lowerright.x, rc.lowerright.y) 0 0 >>>
Field :term:`descriptor`\s can be retrieved from the *class*, they are useful for debugging because they can provide useful information. See :class:`CField`::
>>> POINT.x <ctypes.CField 'x' type=c_int, ofs=0, size=4> >>> POINT.y <ctypes.CField 'y' type=c_int, ofs=4, size=4> >>>
:mod:`!ctypes` does not support passing unions or structures with bit-fields to functions by value. While this may work on 32-bit x86, it's not guaranteed by the library to work in the general case. Unions and structures with bit-fields should always be passed to functions by pointer.
By default, Structure and Union fields are laid out in the same way the C compiler does it. It is possible to override this behavior entirely by specifying a :attr:`~Structure._layout_` class attribute in the subclass definition; see the attribute documentation for details.
:mod:`!ctypes` uses the native byte order for Structures and Unions. To build structures with non-native byte order, you can use one of the :class:`BigEndianStructure`, :class:`LittleEndianStructure`, :class:`BigEndianUnion`, and :class:`LittleEndianUnion` base classes. These classes cannot contain pointer fields.
Bit fields in structures and unions
It is possible to create structures and unions containing bit fields. Bit fields are only possible for integer fields, the bit width is specified as the third item in the :attr:`~Structure._fields_` tuples::
>>> class Int(Structure): ... _fields_ = [("first_16", c_int, 16), ... ("second_16", c_int, 16)] ... >>> print(Int.first_16) <ctypes.CField 'first_16' type=c_int, ofs=0, bit_size=16, bit_offset=0> >>> print(Int.second_16) <ctypes.CField 'second_16' type=c_int, ofs=0, bit_size=16, bit_offset=16>
It is important to note that bit field allocation and layout in memory are not defined as a C standard; their implementation is compiler-specific. By default, Python will attempt to match the behavior of a "native" compiler for the current platform. See the :attr:`~Structure._layout_` attribute for details on the default behavior and how to change it.
>>> from ctypes import * >>> class POINT(Structure): ... _fields_ = ("x", c_int), ("y", c_int) ... >>> class MyStruct(Structure): ... _fields_ = [("a", c_int), ... ("b", c_float), ... ("point_array", POINT * 4)] >>> >>> print(len(MyStruct().point_array)) 4 >>>
Usually, ctypes does strict type checking. This means, if you have ``POINTER(c_int)`` in the :attr:`~_CFuncPtr.argtypes` list of a function or as the type of a member field in a structure definition, only instances of exactly the same type are accepted. There are some exceptions to this rule, where ctypes accepts other objects. For example, you can pass compatible array instances instead of pointer types. So, for ``POINTER(c_int)``, ctypes accepts an array of c_int::
>>> class Bar(Structure): ... _fields_ = [("count", c_int), ("values", POINTER(c_int))] ... >>> bar = Bar() >>> bar.values = (c_int * 3)(1, 2, 3) >>> bar.count = 3 >>> for i in range(bar.count): ... print(bar.values[i]) ... 1 2 3 >>>
To set a POINTER type field to ``NULL``, you can assign ``None``::
Sometimes you have instances of incompatible types. In C, you can cast one type into another type. :mod:`!ctypes` provides a :func:`cast` function which can be used in the same way. The ``Bar`` structure defined above accepts ``POINTER(c_int)`` pointers or :class:`c_int` arrays for its ``values`` field, but not instances of other types::
So, :func:`cast` can be used to assign to the ``values`` field of ``Bar`` the structure::
>>> class cell(Structure): ... _fields_ = [("name", c_char_p), ... ("next", POINTER(cell))] ... Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 2, in cell NameError: name 'cell' is not defined >>>
because the new ``class cell`` is not available in the class statement itself. In :mod:`!ctypes`, we can define the ``cell`` class and set the :attr:`~Structure._fields_` attribute later, after the class statement::
>>> from ctypes import * >>> class cell(Structure): ... pass ... >>> cell._fields_ = [("name", c_char_p), ... ("next", POINTER(cell))] >>>
>>> from ctypes import * >>> >>> class struct_frozen(Structure): ... _fields_ = [("name", c_char_p), ... ("code", POINTER(c_ubyte)), ... ("size", c_int), ... ("is_package", c_int), ... ] ... >>>
>>> from ctypes import * >>> class POINT(Structure): ... _fields_ = ("x", c_int), ("y", c_int) ... >>> class RECT(Structure): ... _fields_ = ("a", POINT), ("b", POINT) ... >>> p1 = POINT(1, 2) >>> p2 = POINT(3, 4) >>> rc = RECT(p1, p2) >>> print(rc.a.x, rc.a.y, rc.b.x, rc.b.y) 1 2 3 4 >>> # now swap the two points >>> rc.a, rc.b = rc.b, rc.a >>> print(rc.a.x, rc.a.y, rc.b.x, rc.b.y) 3 4 3 4 >>>
If the :attr:`~_CFuncPtr.errcheck` function returns the argument tuple it receives unchanged, :mod:`!ctypes` continues the normal processing it does on the output parameters. If you want to return a tuple of window coordinates instead of a ``RECT`` instance, you can retrieve the fields in the function and return them instead, the normal processing will no longer take place::
Fundamental data types, when returned as foreign function call results, or, for example, by retrieving structure field members or array items, are transparently converted to native Python types. In other words, if a foreign function has a :attr:`~_CFuncPtr.restype` of :class:`c_char_p`, you will receive a Python bytes object or ``None`` for a ``NULL`` pointer, *not* a :class:`c_char_p` instance.
:class:`LARGE_INTEGER` and :class:`ULARGE_INTEGER` expose an integer :attr:`!value` attribute, with no ``LowPart``, ``HighPart``, or ``QuadPart`` fields.
A rectangle with ``left``, ``top``, ``right``, and ``bottom`` fields, all of type :class:`LONG`.
A rectangle with ``Left``, ``Top``, ``Right``, and ``Bottom`` fields, all of type :class:`SHORT`.
A point with ``x`` and ``y`` fields, both of type :class:`LONG`.
Dimensions with ``cx`` and ``cy`` fields, both of type :class:`LONG`.
A file time with ``dwLowDateTime`` and ``dwHighDateTime`` fields, both of type :class:`DWORD`.
A Windows message with the following fields:
Field
Field
Structures used by Windows file-search functions, with the following fields. :class:`WIN32_FIND_DATAA` uses :class:`CHAR` for its file names, and :class:`WIN32_FIND_DATAW` uses :class:`WCHAR`.
Fields
Structures and unions with non-native byte order cannot contain pointer type fields, or any other data types containing pointer type fields.
Concrete structure and union types must be created by subclassing one of these types, and at least define a :attr:`_fields_` class variable. :mod:`!ctypes` will create :term:`descriptor`\s which allow reading and writing the fields by direct attribute accesses.
A sequence defining the structure fields. The items must be 2-tuples or 3-tuples. The first item is the name of the field, the second item specifies the type of the field; it can be any ctypes data type.
For integer type fields like :class:`c_int`, a third optional item can be given. It must be a small positive integer defining the bit width of the field.
Field names must be unique within one structure or union. This is not checked, only one field can be accessed when names are repeated.
It is possible to define the :attr:`_fields_` class variable *after* the class statement that defines the Structure subclass, this allows creating data types that directly or indirectly reference themselves::
class List(Structure): pass List._fields_ = [("pnext", POINTER(List)), ... ]
The :attr:`!_fields_` class variable can only be set once. Later assignments will raise an :exc:`AttributeError`.
Additionally, the :attr:`!_fields_` class variable must be defined before the structure or union type is first used, for example when an instance or subclass is created. Later assignments to :attr:`!_fields_` will raise an :exc:`AttributeError`. If :attr:`!_fields_` has not been set before such use, the structure or union will have no own fields, as if :attr:`!_fields_` was empty.
Sub-subclasses of structure types inherit the fields of the base class plus the :attr:`_fields_` defined in the sub-subclass, if any.
An optional small integer that allows overriding the alignment of structure fields in the instance.
:attr:`!_pack_` must already be defined when :attr:`_fields_` is assigned, otherwise it will have no effect.
:attr:`!_align_` must already be defined when :attr:`_fields_` is assigned, otherwise it will have no effect.
:attr:`!_layout_` must already be defined when :attr:`~Structure._fields_` is assigned, otherwise it will have no effect.
An optional sequence that lists the names of unnamed (anonymous) fields. :attr:`_anonymous_` must be already defined when :attr:`_fields_` is assigned, otherwise it will have no effect.
The fields listed in this variable must be structure or union type fields. :mod:`!ctypes` will create descriptors in the structure type that allows accessing the nested fields directly, without the need to create the structure or union field.
class TYPEDESC(Structure): pass class _U(Union): _fields_ = [("lptdesc", POINTER(TYPEDESC)), ("lpadesc", POINTER(ARRAYDESC)), ("hreftype", HREFTYPE)] TYPEDESC._anonymous_ = ("u",) TYPEDESC._fields_ = [("u", _U), ("vt", VARTYPE)]
The ``TYPEDESC`` structure describes a COM data type, the ``vt`` field specifies which one of the union fields is valid. Since the ``u`` field is defined as anonymous field, it is now possible to access the members directly off the TYPEDESC instance. ``td.lptdesc`` and ``td.u.lptdesc`` are equivalent, but the former is faster since it does not need to create a temporary union instance::
It is possible to define sub-subclasses of structures, they inherit the fields of the base class. If the subclass definition has a separate :attr:`_fields_` variable, the fields specified in this are appended to the fields of the base class.
Structure and union constructors accept both positional and keyword arguments. Positional arguments are used to initialize member fields in the same order as they are appear in :attr:`_fields_`. Keyword arguments in the constructor are interpreted as attribute assignments, so they will initialize :attr:`_fields_` with the same name, or create new attributes for names not present in :attr:`_fields_`.
Descriptor for fields of a :class:`Structure` and :class:`Union`. For example::
>>> class Color(Structure): ... _fields_ = ( ... ('red', c_uint8), ... ('green', c_uint8), ... ('blue', c_uint8), ... ('intense', c_bool, 1), ... ('blinking', c_bool, 1), ... ) ... >>> Color.red <ctypes.CField 'red' type=c_ubyte, ofs=0, size=1> >>> Color.green.type <class 'ctypes.c_ubyte'> >>> Color.blue.byte_offset 2 >>> Color.intense <ctypes.CField 'intense' type=c_bool, ofs=3, bit_size=1, bit_offset=0> >>> Color.blinking.bit_offset 1
:class:`!CField` objects are created via :attr:`~Structure._fields_`; do not instantiate the class directly.
Previously, descriptors only had ``offset`` and ``size`` attributes and a readable string representation; the :class:`!CField` class was not available directly.
Name of the field, as a string.
Type of the field, as a :ref:`ctypes class <ctypes-data-types>`.
Offset of the field, in bytes.
For bitfields, this is the offset of the underlying byte-aligned *storage unit*; see :attr:`~CField.bit_offset`.
Size of the field, in bytes.
For bitfields, this is the size of the underlying *storage unit*. Typically, it has the same size as the bitfield's type.
For non-bitfields, equivalent to :attr:`~CField.byte_size`.
For bitfields, this contains a backwards-compatible bit-packed value that combines :attr:`~CField.bit_size` and :attr:`~CField.bit_offset`. Prefer using the explicit attributes instead.
True if this is a bitfield.
The location of a bitfield within its *storage unit*, that is, within :attr:`~CField.byte_size` bytes of memory starting at :attr:`~CField.byte_offset`.
To get the field's value, read the storage unit as an integer, :ref:`shift right <shifting>` by :attr:`!bit_offset` and take the :attr:`!bit_size` least significant bits.
For non-bitfields, :attr:`!bit_offset` is zero and :attr:`!bit_size` is equal to ``byte_size * 8``.
True if this field is anonymous, that is, it contains nested sub-fields that should be merged into a containing structure or union.