xref: /third_party/python/Doc/c-api/buffer.rst (revision 7db96d56)
17db96d56Sopenharmony_ci.. highlight:: c
27db96d56Sopenharmony_ci
37db96d56Sopenharmony_ci.. index::
47db96d56Sopenharmony_ci   single: buffer protocol
57db96d56Sopenharmony_ci   single: buffer interface; (see buffer protocol)
67db96d56Sopenharmony_ci   single: buffer object; (see buffer protocol)
77db96d56Sopenharmony_ci
87db96d56Sopenharmony_ci.. _bufferobjects:
97db96d56Sopenharmony_ci
107db96d56Sopenharmony_ciBuffer Protocol
117db96d56Sopenharmony_ci---------------
127db96d56Sopenharmony_ci
137db96d56Sopenharmony_ci.. sectionauthor:: Greg Stein <gstein@lyra.org>
147db96d56Sopenharmony_ci.. sectionauthor:: Benjamin Peterson
157db96d56Sopenharmony_ci.. sectionauthor:: Stefan Krah
167db96d56Sopenharmony_ci
177db96d56Sopenharmony_ci
187db96d56Sopenharmony_ciCertain objects available in Python wrap access to an underlying memory
197db96d56Sopenharmony_ciarray or *buffer*.  Such objects include the built-in :class:`bytes` and
207db96d56Sopenharmony_ci:class:`bytearray`, and some extension types like :class:`array.array`.
217db96d56Sopenharmony_ciThird-party libraries may define their own types for special purposes, such
227db96d56Sopenharmony_cias image processing or numeric analysis.
237db96d56Sopenharmony_ci
247db96d56Sopenharmony_ciWhile each of these types have their own semantics, they share the common
257db96d56Sopenharmony_cicharacteristic of being backed by a possibly large memory buffer.  It is
267db96d56Sopenharmony_cithen desirable, in some situations, to access that buffer directly and
277db96d56Sopenharmony_ciwithout intermediate copying.
287db96d56Sopenharmony_ci
297db96d56Sopenharmony_ciPython provides such a facility at the C level in the form of the :ref:`buffer
307db96d56Sopenharmony_ciprotocol <bufferobjects>`.  This protocol has two sides:
317db96d56Sopenharmony_ci
327db96d56Sopenharmony_ci.. index:: single: PyBufferProcs
337db96d56Sopenharmony_ci
347db96d56Sopenharmony_ci- on the producer side, a type can export a "buffer interface" which allows
357db96d56Sopenharmony_ci  objects of that type to expose information about their underlying buffer.
367db96d56Sopenharmony_ci  This interface is described in the section :ref:`buffer-structs`;
377db96d56Sopenharmony_ci
387db96d56Sopenharmony_ci- on the consumer side, several means are available to obtain a pointer to
397db96d56Sopenharmony_ci  the raw underlying data of an object (for example a method parameter).
407db96d56Sopenharmony_ci
417db96d56Sopenharmony_ciSimple objects such as :class:`bytes` and :class:`bytearray` expose their
427db96d56Sopenharmony_ciunderlying buffer in byte-oriented form.  Other forms are possible; for example,
437db96d56Sopenharmony_cithe elements exposed by an :class:`array.array` can be multi-byte values.
447db96d56Sopenharmony_ci
457db96d56Sopenharmony_ciAn example consumer of the buffer interface is the :meth:`~io.BufferedIOBase.write`
467db96d56Sopenharmony_cimethod of file objects: any object that can export a series of bytes through
477db96d56Sopenharmony_cithe buffer interface can be written to a file.  While :meth:`write` only
487db96d56Sopenharmony_cineeds read-only access to the internal contents of the object passed to it,
497db96d56Sopenharmony_ciother methods such as :meth:`~io.BufferedIOBase.readinto` need write access
507db96d56Sopenharmony_cito the contents of their argument.  The buffer interface allows objects to
517db96d56Sopenharmony_ciselectively allow or reject exporting of read-write and read-only buffers.
527db96d56Sopenharmony_ci
537db96d56Sopenharmony_ciThere are two ways for a consumer of the buffer interface to acquire a buffer
547db96d56Sopenharmony_ciover a target object:
557db96d56Sopenharmony_ci
567db96d56Sopenharmony_ci* call :c:func:`PyObject_GetBuffer` with the right parameters;
577db96d56Sopenharmony_ci
587db96d56Sopenharmony_ci* call :c:func:`PyArg_ParseTuple` (or one of its siblings) with one of the
597db96d56Sopenharmony_ci  ``y*``, ``w*`` or ``s*`` :ref:`format codes <arg-parsing>`.
607db96d56Sopenharmony_ci
617db96d56Sopenharmony_ciIn both cases, :c:func:`PyBuffer_Release` must be called when the buffer
627db96d56Sopenharmony_ciisn't needed anymore.  Failure to do so could lead to various issues such as
637db96d56Sopenharmony_ciresource leaks.
647db96d56Sopenharmony_ci
657db96d56Sopenharmony_ci
667db96d56Sopenharmony_ci.. _buffer-structure:
677db96d56Sopenharmony_ci
687db96d56Sopenharmony_ciBuffer structure
697db96d56Sopenharmony_ci================
707db96d56Sopenharmony_ci
717db96d56Sopenharmony_ciBuffer structures (or simply "buffers") are useful as a way to expose the
727db96d56Sopenharmony_cibinary data from another object to the Python programmer.  They can also be
737db96d56Sopenharmony_ciused as a zero-copy slicing mechanism.  Using their ability to reference a
747db96d56Sopenharmony_ciblock of memory, it is possible to expose any data to the Python programmer
757db96d56Sopenharmony_ciquite easily.  The memory could be a large, constant array in a C extension,
767db96d56Sopenharmony_ciit could be a raw block of memory for manipulation before passing to an
777db96d56Sopenharmony_cioperating system library, or it could be used to pass around structured data
787db96d56Sopenharmony_ciin its native, in-memory format.
797db96d56Sopenharmony_ci
807db96d56Sopenharmony_ciContrary to most data types exposed by the Python interpreter, buffers
817db96d56Sopenharmony_ciare not :c:type:`PyObject` pointers but rather simple C structures.  This
827db96d56Sopenharmony_ciallows them to be created and copied very simply.  When a generic wrapper
837db96d56Sopenharmony_ciaround a buffer is needed, a :ref:`memoryview <memoryview-objects>` object
847db96d56Sopenharmony_cican be created.
857db96d56Sopenharmony_ci
867db96d56Sopenharmony_ciFor short instructions how to write an exporting object, see
877db96d56Sopenharmony_ci:ref:`Buffer Object Structures <buffer-structs>`. For obtaining
887db96d56Sopenharmony_cia buffer, see :c:func:`PyObject_GetBuffer`.
897db96d56Sopenharmony_ci
907db96d56Sopenharmony_ci.. c:type:: Py_buffer
917db96d56Sopenharmony_ci
927db96d56Sopenharmony_ci   .. c:member:: void *buf
937db96d56Sopenharmony_ci
947db96d56Sopenharmony_ci      A pointer to the start of the logical structure described by the buffer
957db96d56Sopenharmony_ci      fields. This can be any location within the underlying physical memory
967db96d56Sopenharmony_ci      block of the exporter. For example, with negative :c:member:`~Py_buffer.strides`
977db96d56Sopenharmony_ci      the value may point to the end of the memory block.
987db96d56Sopenharmony_ci
997db96d56Sopenharmony_ci      For :term:`contiguous` arrays, the value points to the beginning of
1007db96d56Sopenharmony_ci      the memory block.
1017db96d56Sopenharmony_ci
1027db96d56Sopenharmony_ci   .. c:member:: PyObject *obj
1037db96d56Sopenharmony_ci
1047db96d56Sopenharmony_ci      A new reference to the exporting object. The reference is owned by
1057db96d56Sopenharmony_ci      the consumer and automatically decremented and set to ``NULL`` by
1067db96d56Sopenharmony_ci      :c:func:`PyBuffer_Release`. The field is the equivalent of the return
1077db96d56Sopenharmony_ci      value of any standard C-API function.
1087db96d56Sopenharmony_ci
1097db96d56Sopenharmony_ci      As a special case, for *temporary* buffers that are wrapped by
1107db96d56Sopenharmony_ci      :c:func:`PyMemoryView_FromBuffer` or :c:func:`PyBuffer_FillInfo`
1117db96d56Sopenharmony_ci      this field is ``NULL``. In general, exporting objects MUST NOT
1127db96d56Sopenharmony_ci      use this scheme.
1137db96d56Sopenharmony_ci
1147db96d56Sopenharmony_ci   .. c:member:: Py_ssize_t len
1157db96d56Sopenharmony_ci
1167db96d56Sopenharmony_ci      ``product(shape) * itemsize``. For contiguous arrays, this is the length
1177db96d56Sopenharmony_ci      of the underlying memory block. For non-contiguous arrays, it is the length
1187db96d56Sopenharmony_ci      that the logical structure would have if it were copied to a contiguous
1197db96d56Sopenharmony_ci      representation.
1207db96d56Sopenharmony_ci
1217db96d56Sopenharmony_ci      Accessing ``((char *)buf)[0] up to ((char *)buf)[len-1]`` is only valid
1227db96d56Sopenharmony_ci      if the buffer has been obtained by a request that guarantees contiguity. In
1237db96d56Sopenharmony_ci      most cases such a request will be :c:macro:`PyBUF_SIMPLE` or :c:macro:`PyBUF_WRITABLE`.
1247db96d56Sopenharmony_ci
1257db96d56Sopenharmony_ci   .. c:member:: int readonly
1267db96d56Sopenharmony_ci
1277db96d56Sopenharmony_ci      An indicator of whether the buffer is read-only. This field is controlled
1287db96d56Sopenharmony_ci      by the :c:macro:`PyBUF_WRITABLE` flag.
1297db96d56Sopenharmony_ci
1307db96d56Sopenharmony_ci   .. c:member:: Py_ssize_t itemsize
1317db96d56Sopenharmony_ci
1327db96d56Sopenharmony_ci      Item size in bytes of a single element. Same as the value of :func:`struct.calcsize`
1337db96d56Sopenharmony_ci      called on non-``NULL`` :c:member:`~Py_buffer.format` values.
1347db96d56Sopenharmony_ci
1357db96d56Sopenharmony_ci      Important exception: If a consumer requests a buffer without the
1367db96d56Sopenharmony_ci      :c:macro:`PyBUF_FORMAT` flag, :c:member:`~Py_buffer.format` will
1377db96d56Sopenharmony_ci      be set to  ``NULL``,  but :c:member:`~Py_buffer.itemsize` still has
1387db96d56Sopenharmony_ci      the value for the original format.
1397db96d56Sopenharmony_ci
1407db96d56Sopenharmony_ci      If :c:member:`~Py_buffer.shape` is present, the equality
1417db96d56Sopenharmony_ci      ``product(shape) * itemsize == len`` still holds and the consumer
1427db96d56Sopenharmony_ci      can use :c:member:`~Py_buffer.itemsize` to navigate the buffer.
1437db96d56Sopenharmony_ci
1447db96d56Sopenharmony_ci      If :c:member:`~Py_buffer.shape` is ``NULL`` as a result of a :c:macro:`PyBUF_SIMPLE`
1457db96d56Sopenharmony_ci      or a :c:macro:`PyBUF_WRITABLE` request, the consumer must disregard
1467db96d56Sopenharmony_ci      :c:member:`~Py_buffer.itemsize` and assume ``itemsize == 1``.
1477db96d56Sopenharmony_ci
1487db96d56Sopenharmony_ci   .. c:member:: const char *format
1497db96d56Sopenharmony_ci
1507db96d56Sopenharmony_ci      A *NUL* terminated string in :mod:`struct` module style syntax describing
1517db96d56Sopenharmony_ci      the contents of a single item. If this is ``NULL``, ``"B"`` (unsigned bytes)
1527db96d56Sopenharmony_ci      is assumed.
1537db96d56Sopenharmony_ci
1547db96d56Sopenharmony_ci      This field is controlled by the :c:macro:`PyBUF_FORMAT` flag.
1557db96d56Sopenharmony_ci
1567db96d56Sopenharmony_ci   .. c:member:: int ndim
1577db96d56Sopenharmony_ci
1587db96d56Sopenharmony_ci      The number of dimensions the memory represents as an n-dimensional array.
1597db96d56Sopenharmony_ci      If it is ``0``, :c:member:`~Py_buffer.buf` points to a single item representing
1607db96d56Sopenharmony_ci      a scalar. In this case, :c:member:`~Py_buffer.shape`, :c:member:`~Py_buffer.strides`
1617db96d56Sopenharmony_ci      and :c:member:`~Py_buffer.suboffsets` MUST be ``NULL``.
1627db96d56Sopenharmony_ci
1637db96d56Sopenharmony_ci      The macro :c:macro:`PyBUF_MAX_NDIM` limits the maximum number of dimensions
1647db96d56Sopenharmony_ci      to 64. Exporters MUST respect this limit, consumers of multi-dimensional
1657db96d56Sopenharmony_ci      buffers SHOULD be able to handle up to :c:macro:`PyBUF_MAX_NDIM` dimensions.
1667db96d56Sopenharmony_ci
1677db96d56Sopenharmony_ci   .. c:member:: Py_ssize_t *shape
1687db96d56Sopenharmony_ci
1697db96d56Sopenharmony_ci      An array of :c:type:`Py_ssize_t` of length :c:member:`~Py_buffer.ndim`
1707db96d56Sopenharmony_ci      indicating the shape of the memory as an n-dimensional array. Note that
1717db96d56Sopenharmony_ci      ``shape[0] * ... * shape[ndim-1] * itemsize`` MUST be equal to
1727db96d56Sopenharmony_ci      :c:member:`~Py_buffer.len`.
1737db96d56Sopenharmony_ci
1747db96d56Sopenharmony_ci      Shape values are restricted to ``shape[n] >= 0``. The case
1757db96d56Sopenharmony_ci      ``shape[n] == 0`` requires special attention. See `complex arrays`_
1767db96d56Sopenharmony_ci      for further information.
1777db96d56Sopenharmony_ci
1787db96d56Sopenharmony_ci      The shape array is read-only for the consumer.
1797db96d56Sopenharmony_ci
1807db96d56Sopenharmony_ci   .. c:member:: Py_ssize_t *strides
1817db96d56Sopenharmony_ci
1827db96d56Sopenharmony_ci      An array of :c:type:`Py_ssize_t` of length :c:member:`~Py_buffer.ndim`
1837db96d56Sopenharmony_ci      giving the number of bytes to skip to get to a new element in each
1847db96d56Sopenharmony_ci      dimension.
1857db96d56Sopenharmony_ci
1867db96d56Sopenharmony_ci      Stride values can be any integer. For regular arrays, strides are
1877db96d56Sopenharmony_ci      usually positive, but a consumer MUST be able to handle the case
1887db96d56Sopenharmony_ci      ``strides[n] <= 0``. See `complex arrays`_ for further information.
1897db96d56Sopenharmony_ci
1907db96d56Sopenharmony_ci      The strides array is read-only for the consumer.
1917db96d56Sopenharmony_ci
1927db96d56Sopenharmony_ci   .. c:member:: Py_ssize_t *suboffsets
1937db96d56Sopenharmony_ci
1947db96d56Sopenharmony_ci      An array of :c:type:`Py_ssize_t` of length :c:member:`~Py_buffer.ndim`.
1957db96d56Sopenharmony_ci      If ``suboffsets[n] >= 0``, the values stored along the nth dimension are
1967db96d56Sopenharmony_ci      pointers and the suboffset value dictates how many bytes to add to each
1977db96d56Sopenharmony_ci      pointer after de-referencing. A suboffset value that is negative
1987db96d56Sopenharmony_ci      indicates that no de-referencing should occur (striding in a contiguous
1997db96d56Sopenharmony_ci      memory block).
2007db96d56Sopenharmony_ci
2017db96d56Sopenharmony_ci      If all suboffsets are negative (i.e. no de-referencing is needed), then
2027db96d56Sopenharmony_ci      this field must be ``NULL`` (the default value).
2037db96d56Sopenharmony_ci
2047db96d56Sopenharmony_ci      This type of array representation is used by the Python Imaging Library
2057db96d56Sopenharmony_ci      (PIL). See `complex arrays`_ for further information how to access elements
2067db96d56Sopenharmony_ci      of such an array.
2077db96d56Sopenharmony_ci
2087db96d56Sopenharmony_ci      The suboffsets array is read-only for the consumer.
2097db96d56Sopenharmony_ci
2107db96d56Sopenharmony_ci   .. c:member:: void *internal
2117db96d56Sopenharmony_ci
2127db96d56Sopenharmony_ci      This is for use internally by the exporting object. For example, this
2137db96d56Sopenharmony_ci      might be re-cast as an integer by the exporter and used to store flags
2147db96d56Sopenharmony_ci      about whether or not the shape, strides, and suboffsets arrays must be
2157db96d56Sopenharmony_ci      freed when the buffer is released. The consumer MUST NOT alter this
2167db96d56Sopenharmony_ci      value.
2177db96d56Sopenharmony_ci
2187db96d56Sopenharmony_ci.. _buffer-request-types:
2197db96d56Sopenharmony_ci
2207db96d56Sopenharmony_ciBuffer request types
2217db96d56Sopenharmony_ci====================
2227db96d56Sopenharmony_ci
2237db96d56Sopenharmony_ciBuffers are usually obtained by sending a buffer request to an exporting
2247db96d56Sopenharmony_ciobject via :c:func:`PyObject_GetBuffer`. Since the complexity of the logical
2257db96d56Sopenharmony_cistructure of the memory can vary drastically, the consumer uses the *flags*
2267db96d56Sopenharmony_ciargument to specify the exact buffer type it can handle.
2277db96d56Sopenharmony_ci
2287db96d56Sopenharmony_ciAll :c:data:`Py_buffer` fields are unambiguously defined by the request
2297db96d56Sopenharmony_citype.
2307db96d56Sopenharmony_ci
2317db96d56Sopenharmony_cirequest-independent fields
2327db96d56Sopenharmony_ci~~~~~~~~~~~~~~~~~~~~~~~~~~
2337db96d56Sopenharmony_ciThe following fields are not influenced by *flags* and must always be filled in
2347db96d56Sopenharmony_ciwith the correct values: :c:member:`~Py_buffer.obj`, :c:member:`~Py_buffer.buf`,
2357db96d56Sopenharmony_ci:c:member:`~Py_buffer.len`, :c:member:`~Py_buffer.itemsize`, :c:member:`~Py_buffer.ndim`.
2367db96d56Sopenharmony_ci
2377db96d56Sopenharmony_ci
2387db96d56Sopenharmony_cireadonly, format
2397db96d56Sopenharmony_ci~~~~~~~~~~~~~~~~
2407db96d56Sopenharmony_ci
2417db96d56Sopenharmony_ci   .. c:macro:: PyBUF_WRITABLE
2427db96d56Sopenharmony_ci
2437db96d56Sopenharmony_ci      Controls the :c:member:`~Py_buffer.readonly` field. If set, the exporter
2447db96d56Sopenharmony_ci      MUST provide a writable buffer or else report failure. Otherwise, the
2457db96d56Sopenharmony_ci      exporter MAY provide either a read-only or writable buffer, but the choice
2467db96d56Sopenharmony_ci      MUST be consistent for all consumers.
2477db96d56Sopenharmony_ci
2487db96d56Sopenharmony_ci   .. c:macro:: PyBUF_FORMAT
2497db96d56Sopenharmony_ci
2507db96d56Sopenharmony_ci      Controls the :c:member:`~Py_buffer.format` field. If set, this field MUST
2517db96d56Sopenharmony_ci      be filled in correctly. Otherwise, this field MUST be ``NULL``.
2527db96d56Sopenharmony_ci
2537db96d56Sopenharmony_ci
2547db96d56Sopenharmony_ci:c:macro:`PyBUF_WRITABLE` can be \|'d to any of the flags in the next section.
2557db96d56Sopenharmony_ciSince :c:macro:`PyBUF_SIMPLE` is defined as 0, :c:macro:`PyBUF_WRITABLE`
2567db96d56Sopenharmony_cican be used as a stand-alone flag to request a simple writable buffer.
2577db96d56Sopenharmony_ci
2587db96d56Sopenharmony_ci:c:macro:`PyBUF_FORMAT` can be \|'d to any of the flags except :c:macro:`PyBUF_SIMPLE`.
2597db96d56Sopenharmony_ciThe latter already implies format ``B`` (unsigned bytes).
2607db96d56Sopenharmony_ci
2617db96d56Sopenharmony_ci
2627db96d56Sopenharmony_cishape, strides, suboffsets
2637db96d56Sopenharmony_ci~~~~~~~~~~~~~~~~~~~~~~~~~~
2647db96d56Sopenharmony_ci
2657db96d56Sopenharmony_ciThe flags that control the logical structure of the memory are listed
2667db96d56Sopenharmony_ciin decreasing order of complexity. Note that each flag contains all bits
2677db96d56Sopenharmony_ciof the flags below it.
2687db96d56Sopenharmony_ci
2697db96d56Sopenharmony_ci.. tabularcolumns:: |p{0.35\linewidth}|l|l|l|
2707db96d56Sopenharmony_ci
2717db96d56Sopenharmony_ci+-----------------------------+-------+---------+------------+
2727db96d56Sopenharmony_ci|  Request                    | shape | strides | suboffsets |
2737db96d56Sopenharmony_ci+=============================+=======+=========+============+
2747db96d56Sopenharmony_ci| .. c:macro:: PyBUF_INDIRECT |  yes  |   yes   | if needed  |
2757db96d56Sopenharmony_ci+-----------------------------+-------+---------+------------+
2767db96d56Sopenharmony_ci| .. c:macro:: PyBUF_STRIDES  |  yes  |   yes   |    NULL    |
2777db96d56Sopenharmony_ci+-----------------------------+-------+---------+------------+
2787db96d56Sopenharmony_ci| .. c:macro:: PyBUF_ND       |  yes  |   NULL  |    NULL    |
2797db96d56Sopenharmony_ci+-----------------------------+-------+---------+------------+
2807db96d56Sopenharmony_ci| .. c:macro:: PyBUF_SIMPLE   |  NULL |   NULL  |    NULL    |
2817db96d56Sopenharmony_ci+-----------------------------+-------+---------+------------+
2827db96d56Sopenharmony_ci
2837db96d56Sopenharmony_ci
2847db96d56Sopenharmony_ci.. index:: contiguous, C-contiguous, Fortran contiguous
2857db96d56Sopenharmony_ci
2867db96d56Sopenharmony_cicontiguity requests
2877db96d56Sopenharmony_ci~~~~~~~~~~~~~~~~~~~
2887db96d56Sopenharmony_ci
2897db96d56Sopenharmony_ciC or Fortran :term:`contiguity <contiguous>` can be explicitly requested,
2907db96d56Sopenharmony_ciwith and without stride information. Without stride information, the buffer
2917db96d56Sopenharmony_cimust be C-contiguous.
2927db96d56Sopenharmony_ci
2937db96d56Sopenharmony_ci.. tabularcolumns:: |p{0.35\linewidth}|l|l|l|l|
2947db96d56Sopenharmony_ci
2957db96d56Sopenharmony_ci+-----------------------------------+-------+---------+------------+--------+
2967db96d56Sopenharmony_ci|  Request                          | shape | strides | suboffsets | contig |
2977db96d56Sopenharmony_ci+===================================+=======+=========+============+========+
2987db96d56Sopenharmony_ci| .. c:macro:: PyBUF_C_CONTIGUOUS   |  yes  |   yes   |    NULL    |   C    |
2997db96d56Sopenharmony_ci+-----------------------------------+-------+---------+------------+--------+
3007db96d56Sopenharmony_ci| .. c:macro:: PyBUF_F_CONTIGUOUS   |  yes  |   yes   |    NULL    |   F    |
3017db96d56Sopenharmony_ci+-----------------------------------+-------+---------+------------+--------+
3027db96d56Sopenharmony_ci| .. c:macro:: PyBUF_ANY_CONTIGUOUS |  yes  |   yes   |    NULL    | C or F |
3037db96d56Sopenharmony_ci+-----------------------------------+-------+---------+------------+--------+
3047db96d56Sopenharmony_ci| :c:macro:`PyBUF_ND`               |  yes  |   NULL  |    NULL    |   C    |
3057db96d56Sopenharmony_ci+-----------------------------------+-------+---------+------------+--------+
3067db96d56Sopenharmony_ci
3077db96d56Sopenharmony_ci
3087db96d56Sopenharmony_cicompound requests
3097db96d56Sopenharmony_ci~~~~~~~~~~~~~~~~~
3107db96d56Sopenharmony_ci
3117db96d56Sopenharmony_ciAll possible requests are fully defined by some combination of the flags in
3127db96d56Sopenharmony_cithe previous section. For convenience, the buffer protocol provides frequently
3137db96d56Sopenharmony_ciused combinations as single flags.
3147db96d56Sopenharmony_ci
3157db96d56Sopenharmony_ciIn the following table *U* stands for undefined contiguity. The consumer would
3167db96d56Sopenharmony_cihave to call :c:func:`PyBuffer_IsContiguous` to determine contiguity.
3177db96d56Sopenharmony_ci
3187db96d56Sopenharmony_ci.. tabularcolumns:: |p{0.35\linewidth}|l|l|l|l|l|l|
3197db96d56Sopenharmony_ci
3207db96d56Sopenharmony_ci+-------------------------------+-------+---------+------------+--------+----------+--------+
3217db96d56Sopenharmony_ci|  Request                      | shape | strides | suboffsets | contig | readonly | format |
3227db96d56Sopenharmony_ci+===============================+=======+=========+============+========+==========+========+
3237db96d56Sopenharmony_ci| .. c:macro:: PyBUF_FULL       |  yes  |   yes   | if needed  |   U    |     0    |  yes   |
3247db96d56Sopenharmony_ci+-------------------------------+-------+---------+------------+--------+----------+--------+
3257db96d56Sopenharmony_ci| .. c:macro:: PyBUF_FULL_RO    |  yes  |   yes   | if needed  |   U    |  1 or 0  |  yes   |
3267db96d56Sopenharmony_ci+-------------------------------+-------+---------+------------+--------+----------+--------+
3277db96d56Sopenharmony_ci| .. c:macro:: PyBUF_RECORDS    |  yes  |   yes   |    NULL    |   U    |     0    |  yes   |
3287db96d56Sopenharmony_ci+-------------------------------+-------+---------+------------+--------+----------+--------+
3297db96d56Sopenharmony_ci| .. c:macro:: PyBUF_RECORDS_RO |  yes  |   yes   |    NULL    |   U    |  1 or 0  |  yes   |
3307db96d56Sopenharmony_ci+-------------------------------+-------+---------+------------+--------+----------+--------+
3317db96d56Sopenharmony_ci| .. c:macro:: PyBUF_STRIDED    |  yes  |   yes   |    NULL    |   U    |     0    |  NULL  |
3327db96d56Sopenharmony_ci+-------------------------------+-------+---------+------------+--------+----------+--------+
3337db96d56Sopenharmony_ci| .. c:macro:: PyBUF_STRIDED_RO |  yes  |   yes   |    NULL    |   U    |  1 or 0  |  NULL  |
3347db96d56Sopenharmony_ci+-------------------------------+-------+---------+------------+--------+----------+--------+
3357db96d56Sopenharmony_ci| .. c:macro:: PyBUF_CONTIG     |  yes  |   NULL  |    NULL    |   C    |     0    |  NULL  |
3367db96d56Sopenharmony_ci+-------------------------------+-------+---------+------------+--------+----------+--------+
3377db96d56Sopenharmony_ci| .. c:macro:: PyBUF_CONTIG_RO  |  yes  |   NULL  |    NULL    |   C    |  1 or 0  |  NULL  |
3387db96d56Sopenharmony_ci+-------------------------------+-------+---------+------------+--------+----------+--------+
3397db96d56Sopenharmony_ci
3407db96d56Sopenharmony_ci
3417db96d56Sopenharmony_ciComplex arrays
3427db96d56Sopenharmony_ci==============
3437db96d56Sopenharmony_ci
3447db96d56Sopenharmony_ciNumPy-style: shape and strides
3457db96d56Sopenharmony_ci~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3467db96d56Sopenharmony_ci
3477db96d56Sopenharmony_ciThe logical structure of NumPy-style arrays is defined by :c:member:`~Py_buffer.itemsize`,
3487db96d56Sopenharmony_ci:c:member:`~Py_buffer.ndim`, :c:member:`~Py_buffer.shape` and :c:member:`~Py_buffer.strides`.
3497db96d56Sopenharmony_ci
3507db96d56Sopenharmony_ciIf ``ndim == 0``, the memory location pointed to by :c:member:`~Py_buffer.buf` is
3517db96d56Sopenharmony_ciinterpreted as a scalar of size :c:member:`~Py_buffer.itemsize`. In that case,
3527db96d56Sopenharmony_ciboth :c:member:`~Py_buffer.shape` and :c:member:`~Py_buffer.strides` are ``NULL``.
3537db96d56Sopenharmony_ci
3547db96d56Sopenharmony_ciIf :c:member:`~Py_buffer.strides` is ``NULL``, the array is interpreted as
3557db96d56Sopenharmony_cia standard n-dimensional C-array. Otherwise, the consumer must access an
3567db96d56Sopenharmony_cin-dimensional array as follows:
3577db96d56Sopenharmony_ci
3587db96d56Sopenharmony_ci.. code-block:: c
3597db96d56Sopenharmony_ci
3607db96d56Sopenharmony_ci   ptr = (char *)buf + indices[0] * strides[0] + ... + indices[n-1] * strides[n-1];
3617db96d56Sopenharmony_ci   item = *((typeof(item) *)ptr);
3627db96d56Sopenharmony_ci
3637db96d56Sopenharmony_ci
3647db96d56Sopenharmony_ciAs noted above, :c:member:`~Py_buffer.buf` can point to any location within
3657db96d56Sopenharmony_cithe actual memory block. An exporter can check the validity of a buffer with
3667db96d56Sopenharmony_cithis function:
3677db96d56Sopenharmony_ci
3687db96d56Sopenharmony_ci.. code-block:: python
3697db96d56Sopenharmony_ci
3707db96d56Sopenharmony_ci   def verify_structure(memlen, itemsize, ndim, shape, strides, offset):
3717db96d56Sopenharmony_ci       """Verify that the parameters represent a valid array within
3727db96d56Sopenharmony_ci          the bounds of the allocated memory:
3737db96d56Sopenharmony_ci              char *mem: start of the physical memory block
3747db96d56Sopenharmony_ci              memlen: length of the physical memory block
3757db96d56Sopenharmony_ci              offset: (char *)buf - mem
3767db96d56Sopenharmony_ci       """
3777db96d56Sopenharmony_ci       if offset % itemsize:
3787db96d56Sopenharmony_ci           return False
3797db96d56Sopenharmony_ci       if offset < 0 or offset+itemsize > memlen:
3807db96d56Sopenharmony_ci           return False
3817db96d56Sopenharmony_ci       if any(v % itemsize for v in strides):
3827db96d56Sopenharmony_ci           return False
3837db96d56Sopenharmony_ci
3847db96d56Sopenharmony_ci       if ndim <= 0:
3857db96d56Sopenharmony_ci           return ndim == 0 and not shape and not strides
3867db96d56Sopenharmony_ci       if 0 in shape:
3877db96d56Sopenharmony_ci           return True
3887db96d56Sopenharmony_ci
3897db96d56Sopenharmony_ci       imin = sum(strides[j]*(shape[j]-1) for j in range(ndim)
3907db96d56Sopenharmony_ci                  if strides[j] <= 0)
3917db96d56Sopenharmony_ci       imax = sum(strides[j]*(shape[j]-1) for j in range(ndim)
3927db96d56Sopenharmony_ci                  if strides[j] > 0)
3937db96d56Sopenharmony_ci
3947db96d56Sopenharmony_ci       return 0 <= offset+imin and offset+imax+itemsize <= memlen
3957db96d56Sopenharmony_ci
3967db96d56Sopenharmony_ci
3977db96d56Sopenharmony_ciPIL-style: shape, strides and suboffsets
3987db96d56Sopenharmony_ci~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3997db96d56Sopenharmony_ci
4007db96d56Sopenharmony_ciIn addition to the regular items, PIL-style arrays can contain pointers
4017db96d56Sopenharmony_cithat must be followed in order to get to the next element in a dimension.
4027db96d56Sopenharmony_ciFor example, the regular three-dimensional C-array ``char v[2][2][3]`` can
4037db96d56Sopenharmony_cialso be viewed as an array of 2 pointers to 2 two-dimensional arrays:
4047db96d56Sopenharmony_ci``char (*v[2])[2][3]``. In suboffsets representation, those two pointers
4057db96d56Sopenharmony_cican be embedded at the start of :c:member:`~Py_buffer.buf`, pointing
4067db96d56Sopenharmony_cito two ``char x[2][3]`` arrays that can be located anywhere in memory.
4077db96d56Sopenharmony_ci
4087db96d56Sopenharmony_ci
4097db96d56Sopenharmony_ciHere is a function that returns a pointer to the element in an N-D array
4107db96d56Sopenharmony_cipointed to by an N-dimensional index when there are both non-``NULL`` strides
4117db96d56Sopenharmony_ciand suboffsets::
4127db96d56Sopenharmony_ci
4137db96d56Sopenharmony_ci   void *get_item_pointer(int ndim, void *buf, Py_ssize_t *strides,
4147db96d56Sopenharmony_ci                          Py_ssize_t *suboffsets, Py_ssize_t *indices) {
4157db96d56Sopenharmony_ci       char *pointer = (char*)buf;
4167db96d56Sopenharmony_ci       int i;
4177db96d56Sopenharmony_ci       for (i = 0; i < ndim; i++) {
4187db96d56Sopenharmony_ci           pointer += strides[i] * indices[i];
4197db96d56Sopenharmony_ci           if (suboffsets[i] >=0 ) {
4207db96d56Sopenharmony_ci               pointer = *((char**)pointer) + suboffsets[i];
4217db96d56Sopenharmony_ci           }
4227db96d56Sopenharmony_ci       }
4237db96d56Sopenharmony_ci       return (void*)pointer;
4247db96d56Sopenharmony_ci   }
4257db96d56Sopenharmony_ci
4267db96d56Sopenharmony_ci
4277db96d56Sopenharmony_ciBuffer-related functions
4287db96d56Sopenharmony_ci========================
4297db96d56Sopenharmony_ci
4307db96d56Sopenharmony_ci.. c:function:: int PyObject_CheckBuffer(PyObject *obj)
4317db96d56Sopenharmony_ci
4327db96d56Sopenharmony_ci   Return ``1`` if *obj* supports the buffer interface otherwise ``0``.  When ``1`` is
4337db96d56Sopenharmony_ci   returned, it doesn't guarantee that :c:func:`PyObject_GetBuffer` will
4347db96d56Sopenharmony_ci   succeed.  This function always succeeds.
4357db96d56Sopenharmony_ci
4367db96d56Sopenharmony_ci
4377db96d56Sopenharmony_ci.. c:function:: int PyObject_GetBuffer(PyObject *exporter, Py_buffer *view, int flags)
4387db96d56Sopenharmony_ci
4397db96d56Sopenharmony_ci   Send a request to *exporter* to fill in *view* as specified by  *flags*.
4407db96d56Sopenharmony_ci   If the exporter cannot provide a buffer of the exact type, it MUST raise
4417db96d56Sopenharmony_ci   :c:data:`PyExc_BufferError`, set ``view->obj`` to ``NULL`` and
4427db96d56Sopenharmony_ci   return ``-1``.
4437db96d56Sopenharmony_ci
4447db96d56Sopenharmony_ci   On success, fill in *view*, set ``view->obj`` to a new reference
4457db96d56Sopenharmony_ci   to *exporter* and return 0. In the case of chained buffer providers
4467db96d56Sopenharmony_ci   that redirect requests to a single object, ``view->obj`` MAY
4477db96d56Sopenharmony_ci   refer to this object instead of *exporter* (See :ref:`Buffer Object Structures <buffer-structs>`).
4487db96d56Sopenharmony_ci
4497db96d56Sopenharmony_ci   Successful calls to :c:func:`PyObject_GetBuffer` must be paired with calls
4507db96d56Sopenharmony_ci   to :c:func:`PyBuffer_Release`, similar to :c:func:`malloc` and :c:func:`free`.
4517db96d56Sopenharmony_ci   Thus, after the consumer is done with the buffer, :c:func:`PyBuffer_Release`
4527db96d56Sopenharmony_ci   must be called exactly once.
4537db96d56Sopenharmony_ci
4547db96d56Sopenharmony_ci
4557db96d56Sopenharmony_ci.. c:function:: void PyBuffer_Release(Py_buffer *view)
4567db96d56Sopenharmony_ci
4577db96d56Sopenharmony_ci   Release the buffer *view* and decrement the reference count for
4587db96d56Sopenharmony_ci   ``view->obj``. This function MUST be called when the buffer
4597db96d56Sopenharmony_ci   is no longer being used, otherwise reference leaks may occur.
4607db96d56Sopenharmony_ci
4617db96d56Sopenharmony_ci   It is an error to call this function on a buffer that was not obtained via
4627db96d56Sopenharmony_ci   :c:func:`PyObject_GetBuffer`.
4637db96d56Sopenharmony_ci
4647db96d56Sopenharmony_ci
4657db96d56Sopenharmony_ci.. c:function:: Py_ssize_t PyBuffer_SizeFromFormat(const char *format)
4667db96d56Sopenharmony_ci
4677db96d56Sopenharmony_ci   Return the implied :c:data:`~Py_buffer.itemsize` from :c:data:`~Py_buffer.format`.
4687db96d56Sopenharmony_ci   On error, raise an exception and return -1.
4697db96d56Sopenharmony_ci
4707db96d56Sopenharmony_ci   .. versionadded:: 3.9
4717db96d56Sopenharmony_ci
4727db96d56Sopenharmony_ci
4737db96d56Sopenharmony_ci.. c:function:: int PyBuffer_IsContiguous(const Py_buffer *view, char order)
4747db96d56Sopenharmony_ci
4757db96d56Sopenharmony_ci   Return ``1`` if the memory defined by the *view* is C-style (*order* is
4767db96d56Sopenharmony_ci   ``'C'``) or Fortran-style (*order* is ``'F'``) :term:`contiguous` or either one
4777db96d56Sopenharmony_ci   (*order* is ``'A'``).  Return ``0`` otherwise.  This function always succeeds.
4787db96d56Sopenharmony_ci
4797db96d56Sopenharmony_ci
4807db96d56Sopenharmony_ci.. c:function:: void* PyBuffer_GetPointer(const Py_buffer *view, const Py_ssize_t *indices)
4817db96d56Sopenharmony_ci
4827db96d56Sopenharmony_ci   Get the memory area pointed to by the *indices* inside the given *view*.
4837db96d56Sopenharmony_ci   *indices* must point to an array of ``view->ndim`` indices.
4847db96d56Sopenharmony_ci
4857db96d56Sopenharmony_ci
4867db96d56Sopenharmony_ci.. c:function:: int PyBuffer_FromContiguous(const Py_buffer *view, const void *buf, Py_ssize_t len, char fort)
4877db96d56Sopenharmony_ci
4887db96d56Sopenharmony_ci   Copy contiguous *len* bytes from *buf* to *view*.
4897db96d56Sopenharmony_ci   *fort* can be ``'C'`` or ``'F'`` (for C-style or Fortran-style ordering).
4907db96d56Sopenharmony_ci   ``0`` is returned on success, ``-1`` on error.
4917db96d56Sopenharmony_ci
4927db96d56Sopenharmony_ci
4937db96d56Sopenharmony_ci.. c:function:: int PyBuffer_ToContiguous(void *buf, const Py_buffer *src, Py_ssize_t len, char order)
4947db96d56Sopenharmony_ci
4957db96d56Sopenharmony_ci   Copy *len* bytes from *src* to its contiguous representation in *buf*.
4967db96d56Sopenharmony_ci   *order* can be ``'C'`` or ``'F'`` or ``'A'`` (for C-style or Fortran-style
4977db96d56Sopenharmony_ci   ordering or either one). ``0`` is returned on success, ``-1`` on error.
4987db96d56Sopenharmony_ci
4997db96d56Sopenharmony_ci   This function fails if *len* != *src->len*.
5007db96d56Sopenharmony_ci
5017db96d56Sopenharmony_ci
5027db96d56Sopenharmony_ci.. c:function:: int PyObject_CopyData(PyObject *dest, PyObject *src)
5037db96d56Sopenharmony_ci
5047db96d56Sopenharmony_ci   Copy data from *src* to *dest* buffer. Can convert between C-style and
5057db96d56Sopenharmony_ci   or Fortran-style buffers.
5067db96d56Sopenharmony_ci
5077db96d56Sopenharmony_ci   ``0`` is returned on success, ``-1`` on error.
5087db96d56Sopenharmony_ci
5097db96d56Sopenharmony_ci.. c:function:: void PyBuffer_FillContiguousStrides(int ndims, Py_ssize_t *shape, Py_ssize_t *strides, int itemsize, char order)
5107db96d56Sopenharmony_ci
5117db96d56Sopenharmony_ci   Fill the *strides* array with byte-strides of a :term:`contiguous` (C-style if
5127db96d56Sopenharmony_ci   *order* is ``'C'`` or Fortran-style if *order* is ``'F'``) array of the
5137db96d56Sopenharmony_ci   given shape with the given number of bytes per element.
5147db96d56Sopenharmony_ci
5157db96d56Sopenharmony_ci
5167db96d56Sopenharmony_ci.. c:function:: int PyBuffer_FillInfo(Py_buffer *view, PyObject *exporter, void *buf, Py_ssize_t len, int readonly, int flags)
5177db96d56Sopenharmony_ci
5187db96d56Sopenharmony_ci   Handle buffer requests for an exporter that wants to expose *buf* of size *len*
5197db96d56Sopenharmony_ci   with writability set according to *readonly*. *buf* is interpreted as a sequence
5207db96d56Sopenharmony_ci   of unsigned bytes.
5217db96d56Sopenharmony_ci
5227db96d56Sopenharmony_ci   The *flags* argument indicates the request type. This function always fills in
5237db96d56Sopenharmony_ci   *view* as specified by flags, unless *buf* has been designated as read-only
5247db96d56Sopenharmony_ci   and :c:macro:`PyBUF_WRITABLE` is set in *flags*.
5257db96d56Sopenharmony_ci
5267db96d56Sopenharmony_ci   On success, set ``view->obj`` to a new reference to *exporter* and
5277db96d56Sopenharmony_ci   return 0. Otherwise, raise :c:data:`PyExc_BufferError`, set
5287db96d56Sopenharmony_ci   ``view->obj`` to ``NULL`` and return ``-1``;
5297db96d56Sopenharmony_ci
5307db96d56Sopenharmony_ci   If this function is used as part of a :ref:`getbufferproc <buffer-structs>`,
5317db96d56Sopenharmony_ci   *exporter* MUST be set to the exporting object and *flags* must be passed
5327db96d56Sopenharmony_ci   unmodified. Otherwise, *exporter* MUST be ``NULL``.
533