| 1 |
.. highlight:: c |
| 2 |
|
| 3 |
.. index:: |
| 4 |
single: buffer protocol |
| 5 |
single: buffer interface; (see buffer protocol) |
| 6 |
single: buffer object; (see buffer protocol) |
| 7 |
|
| 8 |
.. _bufferobjects: |
| 9 |
|
| 10 |
Buffer Protocol |
| 11 |
--------------- |
| 12 |
|
| 13 |
.. sectionauthor:: Greg Stein <[email protected]> |
| 14 |
.. sectionauthor:: Benjamin Peterson |
| 15 |
.. sectionauthor:: Stefan Krah |
| 16 |
|
| 17 |
|
| 18 |
Certain objects available in Python wrap access to an underlying memory |
| 19 |
array or *buffer*. Such objects include the built-in :class:`bytes` and |
| 20 |
:class:`bytearray`, and some extension types like :class:`array.array`. |
| 21 |
Third-party libraries may define their own types for special purposes, such |
| 22 |
as image processing or numeric analysis. |
| 23 |
|
| 24 |
While each of these types have their own semantics, they share the common |
| 25 |
characteristic of being backed by a possibly large memory buffer. It is |
| 26 |
then desirable, in some situations, to access that buffer directly and |
| 27 |
without intermediate copying. |
| 28 |
|
| 29 |
Python provides such a facility at the C and Python level in the form of the |
| 30 |
:ref:`buffer protocol <bufferobjects>`. This protocol has two sides: |
| 31 |
|
| 32 |
.. index:: single: PyBufferProcs (C type) |
| 33 |
|
| 34 |
- on the producer side, a type can export a "buffer interface" which allows |
| 35 |
objects of that type to expose information about their underlying buffer. |
| 36 |
This interface is described in the section :ref:`buffer-structs`; for |
| 37 |
Python see :ref:`python-buffer-protocol`. |
| 38 |
|
| 39 |
- on the consumer side, several means are available to obtain a pointer to |
| 40 |
the raw underlying data of an object (for example a method parameter). For |
| 41 |
Python see :class:`memoryview`. |
| 42 |
|
| 43 |
Simple objects such as :class:`bytes` and :class:`bytearray` expose their |
| 44 |
underlying buffer in byte-oriented form. Other forms are possible; for example, |
| 45 |
the elements exposed by an :class:`array.array` can be multi-byte values. |
| 46 |
|
| 47 |
An example consumer of the buffer interface is the :meth:`~io.BufferedIOBase.write` |
| 48 |
method of file objects: any object that can export a series of bytes through |
| 49 |
the buffer interface can be written to a file. While :meth:`!write` only |
| 50 |
needs read-only access to the internal contents of the object passed to it, |
| 51 |
other methods such as :meth:`~io.BufferedIOBase.readinto` need write access |
| 52 |
to the contents of their argument. The buffer interface allows objects to |
| 53 |
selectively allow or reject exporting of read-write and read-only buffers. |
| 54 |
|
| 55 |
There are two ways for a consumer of the buffer interface to acquire a buffer |
| 56 |
over a target object: |
| 57 |
|
| 58 |
* call :c:func:`PyObject_GetBuffer` with the right parameters; |
| 59 |
|
| 60 |
* call :c:func:`PyArg_ParseTuple` (or one of its siblings) with one of the |
| 61 |
``y*``, ``w*`` or ``s*`` :ref:`format codes <arg-parsing>`. |
| 62 |
|
| 63 |
In both cases, :c:func:`PyBuffer_Release` must be called when the buffer |
| 64 |
isn't needed anymore. Failure to do so could lead to various issues such as |
| 65 |
resource leaks. |
| 66 |
|
| 67 |
.. versionadded:: 3.12 |
| 68 |
|
| 69 |
The buffer protocol is now accessible in Python, see |
| 70 |
:ref:`python-buffer-protocol` and :class:`memoryview`. |
| 71 |
|
| 72 |
.. _buffer-structure: |
| 73 |
|
| 74 |
Buffer structure |
| 75 |
================ |
| 76 |
|
| 77 |
Buffer structures (or simply "buffers") are useful as a way to expose the |
| 78 |
binary data from another object to the Python programmer. They can also be |
| 79 |
used as a zero-copy slicing mechanism. Using their ability to reference a |
| 80 |
block of memory, it is possible to expose any data to the Python programmer |
| 81 |
quite easily. The memory could be a large, constant array in a C extension, |
| 82 |
it could be a raw block of memory for manipulation before passing to an |
| 83 |
operating system library, or it could be used to pass around structured data |
| 84 |
in its native, in-memory format. |
| 85 |
|
| 86 |
Contrary to most data types exposed by the Python interpreter, buffers |
| 87 |
are not :c:type:`PyObject` pointers but rather simple C structures. This |
| 88 |
allows them to be created and copied very simply. When a generic wrapper |
| 89 |
around a buffer is needed, a :ref:`memoryview <memoryview-objects>` object |
| 90 |
can be created. |
| 91 |
|
| 92 |
For short instructions how to write an exporting object, see |
| 93 |
:ref:`Buffer Object Structures <buffer-structs>`. For obtaining |
| 94 |
a buffer, see :c:func:`PyObject_GetBuffer`. |
| 95 |
|
| 96 |
.. c:type:: Py_buffer |
| 97 |
|
| 98 |
.. c:member:: void *buf |
| 99 |
|
| 100 |
A pointer to the start of the logical structure described by the buffer |
| 101 |
fields. This can be any location within the underlying physical memory |
| 102 |
block of the exporter. For example, with negative :c:member:`~Py_buffer.strides` |
| 103 |
the value may point to the end of the memory block. |
| 104 |
|
| 105 |
For :term:`contiguous` arrays, the value points to the beginning of |
| 106 |
the memory block. |
| 107 |
|
| 108 |
.. c:member:: PyObject *obj |
| 109 |
|
| 110 |
A new reference to the exporting object. The reference is owned by |
| 111 |
the consumer and automatically released |
| 112 |
(i.e. reference count decremented) |
| 113 |
and set to ``NULL`` by |
| 114 |
:c:func:`PyBuffer_Release`. The field is the equivalent of the return |
| 115 |
value of any standard C-API function. |
| 116 |
|
| 117 |
As a special case, for *temporary* buffers that are wrapped by |
| 118 |
:c:func:`PyMemoryView_FromBuffer` or :c:func:`PyBuffer_FillInfo` |
| 119 |
this field is ``NULL``. In general, exporting objects MUST NOT |
| 120 |
use this scheme. |
| 121 |
|
| 122 |
.. c:member:: Py_ssize_t len |
| 123 |
|
| 124 |
``product(shape) * itemsize``. For contiguous arrays, this is the length |
| 125 |
of the underlying memory block. For non-contiguous arrays, it is the length |
| 126 |
that the logical structure would have if it were copied to a contiguous |
| 127 |
representation. |
| 128 |
|
| 129 |
Accessing ``((char *)buf)[0] up to ((char *)buf)[len-1]`` is only valid |
| 130 |
if the buffer has been obtained by a request that guarantees contiguity. In |
| 131 |
most cases such a request will be :c:macro:`PyBUF_SIMPLE` or :c:macro:`PyBUF_WRITABLE`. |
| 132 |
|
| 133 |
.. c:member:: int readonly |
| 134 |
|
| 135 |
An indicator of whether the buffer is read-only. This field is controlled |
| 136 |
by the :c:macro:`PyBUF_WRITABLE` flag. |
| 137 |
|
| 138 |
.. c:member:: Py_ssize_t itemsize |
| 139 |
|
| 140 |
Item size in bytes of a single element. Same as the value of :func:`struct.calcsize` |
| 141 |
called on non-``NULL`` :c:member:`~Py_buffer.format` values. |
| 142 |
|
| 143 |
Important exception: If a consumer requests a buffer without the |
| 144 |
:c:macro:`PyBUF_FORMAT` flag, :c:member:`~Py_buffer.format` will |
| 145 |
be set to ``NULL``, but :c:member:`~Py_buffer.itemsize` still has |
| 146 |
the value for the original format. |
| 147 |
|
| 148 |
If :c:member:`~Py_buffer.shape` is present, the equality |
| 149 |
``product(shape) * itemsize == len`` still holds and the consumer |
| 150 |
can use :c:member:`~Py_buffer.itemsize` to navigate the buffer. |
| 151 |
|
| 152 |
If :c:member:`~Py_buffer.shape` is ``NULL`` as a result of a :c:macro:`PyBUF_SIMPLE` |
| 153 |
or a :c:macro:`PyBUF_WRITABLE` request, the consumer must disregard |
| 154 |
:c:member:`~Py_buffer.itemsize` and assume ``itemsize == 1``. |
| 155 |
|
| 156 |
.. c:member:: char *format |
| 157 |
|
| 158 |
A *NULL* terminated string in :mod:`struct` module style syntax describing |
| 159 |
the contents of a single item. If this is ``NULL``, ``"B"`` (unsigned bytes) |
| 160 |
is assumed. |
| 161 |
|
| 162 |
This field is controlled by the :c:macro:`PyBUF_FORMAT` flag. |
| 163 |
|
| 164 |
.. c:member:: int ndim |
| 165 |
|
| 166 |
The number of dimensions the memory represents as an n-dimensional array. |
| 167 |
If it is ``0``, :c:member:`~Py_buffer.buf` points to a single item representing |
| 168 |
a scalar. In this case, :c:member:`~Py_buffer.shape`, :c:member:`~Py_buffer.strides` |
| 169 |
and :c:member:`~Py_buffer.suboffsets` MUST be ``NULL``. |
| 170 |
The maximum number of dimensions is given by :c:macro:`PyBUF_MAX_NDIM`. |
| 171 |
|
| 172 |
.. c:member:: Py_ssize_t *shape |
| 173 |
|
| 174 |
An array of :c:type:`Py_ssize_t` of length :c:member:`~Py_buffer.ndim` |
| 175 |
indicating the shape of the memory as an n-dimensional array. Note that |
| 176 |
``shape[0] * ... * shape[ndim-1] * itemsize`` MUST be equal to |
| 177 |
:c:member:`~Py_buffer.len`. |
| 178 |
|
| 179 |
Shape values are restricted to ``shape[n] >= 0``. The case |
| 180 |
``shape[n] == 0`` requires special attention. See `complex arrays`_ |
| 181 |
for further information. |
| 182 |
|
| 183 |
The shape array is read-only for the consumer. |
| 184 |
|
| 185 |
.. c:member:: Py_ssize_t *strides |
| 186 |
|
| 187 |
An array of :c:type:`Py_ssize_t` of length :c:member:`~Py_buffer.ndim` |
| 188 |
giving the number of bytes to skip to get to a new element in each |
| 189 |
dimension. |
| 190 |
|
| 191 |
Stride values can be any integer. For regular arrays, strides are |
| 192 |
usually positive, but a consumer MUST be able to handle the case |
| 193 |
``strides[n] <= 0``. See `complex arrays`_ for further information. |
| 194 |
|
| 195 |
The strides array is read-only for the consumer. |
| 196 |
|
| 197 |
.. c:member:: Py_ssize_t *suboffsets |
| 198 |
|
| 199 |
An array of :c:type:`Py_ssize_t` of length :c:member:`~Py_buffer.ndim`. |
| 200 |
If ``suboffsets[n] >= 0``, the values stored along the nth dimension are |
| 201 |
pointers and the suboffset value dictates how many bytes to add to each |
| 202 |
pointer after de-referencing. A suboffset value that is negative |
| 203 |
indicates that no de-referencing should occur (striding in a contiguous |
| 204 |
memory block). |
| 205 |
|
| 206 |
If all suboffsets are negative (i.e. no de-referencing is needed), then |
| 207 |
this field must be ``NULL`` (the default value). |
| 208 |
|
| 209 |
This type of array representation is used by the Python Imaging Library |
| 210 |
(PIL). See `complex arrays`_ for further information how to access elements |
| 211 |
of such an array. |
| 212 |
|
| 213 |
The suboffsets array is read-only for the consumer. |
| 214 |
|
| 215 |
.. c:member:: void *internal |
| 216 |
|
| 217 |
This is for use internally by the exporting object. For example, this |
| 218 |
might be re-cast as an integer by the exporter and used to store flags |
| 219 |
about whether or not the shape, strides, and suboffsets arrays must be |
| 220 |
freed when the buffer is released. The consumer MUST NOT alter this |
| 221 |
value. |
| 222 |
|
| 223 |
|
| 224 |
Constants: |
| 225 |
|
| 226 |
.. c:macro:: PyBUF_MAX_NDIM |
| 227 |
|
| 228 |
The maximum number of dimensions the memory represents. |
| 229 |
Exporters MUST respect this limit, consumers of multi-dimensional |
| 230 |
buffers SHOULD be able to handle up to :c:macro:`!PyBUF_MAX_NDIM` dimensions. |
| 231 |
Currently set to 64. |
| 232 |
|
| 233 |
|
| 234 |
.. _buffer-request-types: |
| 235 |
|
| 236 |
Buffer request types |
| 237 |
==================== |
| 238 |
|
| 239 |
Buffers are usually obtained by sending a buffer request to an exporting |
| 240 |
object via :c:func:`PyObject_GetBuffer`. Since the complexity of the logical |
| 241 |
structure of the memory can vary drastically, the consumer uses the *flags* |
| 242 |
argument to specify the exact buffer type it can handle. |
| 243 |
|
| 244 |
All :c:type:`Py_buffer` fields are unambiguously defined by the request |
| 245 |
type. |
| 246 |
|
| 247 |
request-independent fields |
| 248 |
~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 249 |
The following fields are not influenced by *flags* and must always be filled in |
| 250 |
with the correct values: :c:member:`~Py_buffer.obj`, :c:member:`~Py_buffer.buf`, |
| 251 |
:c:member:`~Py_buffer.len`, :c:member:`~Py_buffer.itemsize`, :c:member:`~Py_buffer.ndim`. |
| 252 |
|
| 253 |
readonly, format |
| 254 |
~~~~~~~~~~~~~~~~ |
| 255 |
|
| 256 |
.. c:macro:: PyBUF_WRITABLE |
| 257 |
|
| 258 |
Controls the :c:member:`~Py_buffer.readonly` field. If set, the exporter |
| 259 |
MUST provide a writable buffer or else report failure. Otherwise, the |
| 260 |
exporter MAY provide either a read-only or writable buffer, but the choice |
| 261 |
MUST be consistent for all consumers. For example, :c:expr:`PyBUF_SIMPLE | PyBUF_WRITABLE` |
| 262 |
can be used to request a simple writable buffer. |
| 263 |
|
| 264 |
.. c:macro:: PyBUF_WRITEABLE |
| 265 |
|
| 266 |
This is a :term:`soft deprecated` alias to :c:macro:`PyBUF_WRITABLE`. |
| 267 |
|
| 268 |
.. c:macro:: PyBUF_FORMAT |
| 269 |
|
| 270 |
Controls the :c:member:`~Py_buffer.format` field. If set, this field MUST |
| 271 |
be filled in correctly. Otherwise, this field MUST be ``NULL``. |
| 272 |
|
| 273 |
|
| 274 |
:c:macro:`PyBUF_WRITABLE` can be \|'d to any of the flags in the next section. |
| 275 |
Since :c:macro:`PyBUF_SIMPLE` is defined as 0, :c:macro:`PyBUF_WRITABLE` |
| 276 |
can be used as a stand-alone flag to request a simple writable buffer. |
| 277 |
|
| 278 |
:c:macro:`PyBUF_FORMAT` must be \|'d to any of the flags except :c:macro:`PyBUF_SIMPLE`, because |
| 279 |
the latter already implies format ``B`` (unsigned bytes). :c:macro:`!PyBUF_FORMAT` cannot be |
| 280 |
used on its own. |
| 281 |
|
| 282 |
|
| 283 |
shape, strides, suboffsets |
| 284 |
~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 285 |
|
| 286 |
The flags that control the logical structure of the memory are listed |
| 287 |
in decreasing order of complexity. Note that each flag contains all bits |
| 288 |
of the flags below it. |
| 289 |
|
| 290 |
.. tabularcolumns:: |p{0.35\linewidth}|l|l|l| |
| 291 |
|
| 292 |
+-----------------------------+-------+---------+------------+ |
| 293 |
| Request | shape | strides | suboffsets | |
| 294 |
+=============================+=======+=========+============+ |
| 295 |
| .. c:macro:: PyBUF_INDIRECT | yes | yes | if needed | |
| 296 |
+-----------------------------+-------+---------+------------+ |
| 297 |
| .. c:macro:: PyBUF_STRIDES | yes | yes | NULL | |
| 298 |
+-----------------------------+-------+---------+------------+ |
| 299 |
| .. c:macro:: PyBUF_ND | yes | NULL | NULL | |
| 300 |
+-----------------------------+-------+---------+------------+ |
| 301 |
| .. c:macro:: PyBUF_SIMPLE | NULL | NULL | NULL | |
| 302 |
+-----------------------------+-------+---------+------------+ |
| 303 |
|
| 304 |
|
| 305 |
.. index:: contiguous, C-contiguous, Fortran contiguous |
| 306 |
|
| 307 |
contiguity requests |
| 308 |
~~~~~~~~~~~~~~~~~~~ |
| 309 |
|
| 310 |
C or Fortran :term:`contiguity <contiguous>` can be explicitly requested, |
| 311 |
with and without stride information. Without stride information, the buffer |
| 312 |
must be C-contiguous. |
| 313 |
|
| 314 |
.. tabularcolumns:: |p{0.35\linewidth}|l|l|l|l| |
| 315 |
|
| 316 |
+-----------------------------------+-------+---------+------------+--------+ |
| 317 |
| Request | shape | strides | suboffsets | contig | |
| 318 |
+===================================+=======+=========+============+========+ |
| 319 |
| .. c:macro:: PyBUF_C_CONTIGUOUS | yes | yes | NULL | C | |
| 320 |
+-----------------------------------+-------+---------+------------+--------+ |
| 321 |
| .. c:macro:: PyBUF_F_CONTIGUOUS | yes | yes | NULL | F | |
| 322 |
+-----------------------------------+-------+---------+------------+--------+ |
| 323 |
| .. c:macro:: PyBUF_ANY_CONTIGUOUS | yes | yes | NULL | C or F | |
| 324 |
+-----------------------------------+-------+---------+------------+--------+ |
| 325 |
| :c:macro:`PyBUF_ND` | yes | NULL | NULL | C | |
| 326 |
+-----------------------------------+-------+---------+------------+--------+ |
| 327 |
|
| 328 |
|
| 329 |
compound requests |
| 330 |
~~~~~~~~~~~~~~~~~ |
| 331 |
|
| 332 |
All possible requests are fully defined by some combination of the flags in |
| 333 |
the previous section. For convenience, the buffer protocol provides frequently |
| 334 |
used combinations as single flags. |
| 335 |
|
| 336 |
In the following table *U* stands for undefined contiguity. The consumer would |
| 337 |
have to call :c:func:`PyBuffer_IsContiguous` to determine contiguity. |
| 338 |
|
| 339 |
.. tabularcolumns:: |p{0.35\linewidth}|l|l|l|l|l|l| |
| 340 |
|
| 341 |
+-------------------------------+-------+---------+------------+--------+----------+--------+ |
| 342 |
| Request | shape | strides | suboffsets | contig | readonly | format | |
| 343 |
+===============================+=======+=========+============+========+==========+========+ |
| 344 |
| .. c:macro:: PyBUF_FULL | yes | yes | if needed | U | 0 | yes | |
| 345 |
+-------------------------------+-------+---------+------------+--------+----------+--------+ |
| 346 |
| .. c:macro:: PyBUF_FULL_RO | yes | yes | if needed | U | 1 or 0 | yes | |
| 347 |
+-------------------------------+-------+---------+------------+--------+----------+--------+ |
| 348 |
| .. c:macro:: PyBUF_RECORDS | yes | yes | NULL | U | 0 | yes | |
| 349 |
+-------------------------------+-------+---------+------------+--------+----------+--------+ |
| 350 |
| .. c:macro:: PyBUF_RECORDS_RO | yes | yes | NULL | U | 1 or 0 | yes | |
| 351 |
+-------------------------------+-------+---------+------------+--------+----------+--------+ |
| 352 |
| .. c:macro:: PyBUF_STRIDED | yes | yes | NULL | U | 0 | NULL | |
| 353 |
+-------------------------------+-------+---------+------------+--------+----------+--------+ |
| 354 |
| .. c:macro:: PyBUF_STRIDED_RO | yes | yes | NULL | U | 1 or 0 | NULL | |
| 355 |
+-------------------------------+-------+---------+------------+--------+----------+--------+ |
| 356 |
| .. c:macro:: PyBUF_CONTIG | yes | NULL | NULL | C | 0 | NULL | |
| 357 |
+-------------------------------+-------+---------+------------+--------+----------+--------+ |
| 358 |
| .. c:macro:: PyBUF_CONTIG_RO | yes | NULL | NULL | C | 1 or 0 | NULL | |
| 359 |
+-------------------------------+-------+---------+------------+--------+----------+--------+ |
| 360 |
|
| 361 |
|
| 362 |
Complex arrays |
| 363 |
============== |
| 364 |
|
| 365 |
NumPy-style: shape and strides |
| 366 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 367 |
|
| 368 |
The logical structure of NumPy-style arrays is defined by :c:member:`~Py_buffer.itemsize`, |
| 369 |
:c:member:`~Py_buffer.ndim`, :c:member:`~Py_buffer.shape` and :c:member:`~Py_buffer.strides`. |
| 370 |
|
| 371 |
If ``ndim == 0``, the memory location pointed to by :c:member:`~Py_buffer.buf` is |
| 372 |
interpreted as a scalar of size :c:member:`~Py_buffer.itemsize`. In that case, |
| 373 |
both :c:member:`~Py_buffer.shape` and :c:member:`~Py_buffer.strides` are ``NULL``. |
| 374 |
|
| 375 |
If :c:member:`~Py_buffer.strides` is ``NULL``, the array is interpreted as |
| 376 |
a standard n-dimensional C-array. Otherwise, the consumer must access an |
| 377 |
n-dimensional array as follows: |
| 378 |
|
| 379 |
.. code-block:: c |
| 380 |
|
| 381 |
ptr = (char *)buf + indices[0] * strides[0] + ... + indices[n-1] * strides[n-1]; |
| 382 |
item = *((typeof(item) *)ptr); |
| 383 |
|
| 384 |
|
| 385 |
As noted above, :c:member:`~Py_buffer.buf` can point to any location within |
| 386 |
the actual memory block. An exporter can check the validity of a buffer with |
| 387 |
this function: |
| 388 |
|
| 389 |
.. code-block:: python |
| 390 |
|
| 391 |
def verify_structure(memlen, itemsize, ndim, shape, strides, offset): |
| 392 |
"""Verify that the parameters represent a valid array within |
| 393 |
the bounds of the allocated memory: |
| 394 |
char *mem: start of the physical memory block |
| 395 |
memlen: length of the physical memory block |
| 396 |
offset: (char *)buf - mem |
| 397 |
""" |
| 398 |
if offset % itemsize: |
| 399 |
return False |
| 400 |
if offset < 0 or offset+itemsize > memlen: |
| 401 |
return False |
| 402 |
if any(v % itemsize for v in strides): |
| 403 |
return False |
| 404 |
|
| 405 |
if ndim <= 0: |
| 406 |
return ndim == 0 and not shape and not strides |
| 407 |
if 0 in shape: |
| 408 |
return True |
| 409 |
|
| 410 |
imin = sum(strides[j]*(shape[j]-1) for j in range(ndim) |
| 411 |
if strides[j] <= 0) |
| 412 |
imax = sum(strides[j]*(shape[j]-1) for j in range(ndim) |
| 413 |
if strides[j] > 0) |
| 414 |
|
| 415 |
return 0 <= offset+imin and offset+imax+itemsize <= memlen |
| 416 |
|
| 417 |
|
| 418 |
PIL-style: shape, strides and suboffsets |
| 419 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 420 |
|
| 421 |
In addition to the regular items, PIL-style arrays can contain pointers |
| 422 |
that must be followed in order to get to the next element in a dimension. |
| 423 |
For example, the regular three-dimensional C-array ``char v[2][2][3]`` can |
| 424 |
also be viewed as an array of 2 pointers to 2 two-dimensional arrays: |
| 425 |
``char (*v[2])[2][3]``. In suboffsets representation, those two pointers |
| 426 |
can be embedded at the start of :c:member:`~Py_buffer.buf`, pointing |
| 427 |
to two ``char x[2][3]`` arrays that can be located anywhere in memory. |
| 428 |
|
| 429 |
|
| 430 |
Here is a function that returns a pointer to the element in an N-D array |
| 431 |
pointed to by an N-dimensional index when there are both non-``NULL`` strides |
| 432 |
and suboffsets:: |
| 433 |
|
| 434 |
void *get_item_pointer(int ndim, void *buf, Py_ssize_t *strides, |
| 435 |
Py_ssize_t *suboffsets, Py_ssize_t *indices) { |
| 436 |
char *pointer = (char*)buf; |
| 437 |
int i; |
| 438 |
for (i = 0; i < ndim; i++) { |
| 439 |
pointer += strides[i] * indices[i]; |
| 440 |
if (suboffsets[i] >=0 ) { |
| 441 |
pointer = *((char**)pointer) + suboffsets[i]; |
| 442 |
} |
| 443 |
} |
| 444 |
return (void*)pointer; |
| 445 |
} |
| 446 |
|
| 447 |
|
| 448 |
Buffer-related functions |
| 449 |
======================== |
| 450 |
|
| 451 |
.. c:function:: int PyObject_CheckBuffer(PyObject *obj) |
| 452 |
|
| 453 |
Return ``1`` if *obj* supports the buffer interface otherwise ``0``. When ``1`` is |
| 454 |
returned, it doesn't guarantee that :c:func:`PyObject_GetBuffer` will |
| 455 |
succeed. This function always succeeds. |
| 456 |
|
| 457 |
|
| 458 |
.. c:function:: int PyObject_GetBuffer(PyObject *exporter, Py_buffer *view, int flags) |
| 459 |
|
| 460 |
Send a request to *exporter* to fill in *view* as specified by *flags*. |
| 461 |
If the exporter cannot provide a buffer of the exact type, it MUST raise |
| 462 |
:exc:`BufferError`, set ``view->obj`` to ``NULL`` and |
| 463 |
return ``-1``. |
| 464 |
|
| 465 |
On success, fill in *view*, set ``view->obj`` to a new reference |
| 466 |
to *exporter* and return 0. In the case of chained buffer providers |
| 467 |
that redirect requests to a single object, ``view->obj`` MAY |
| 468 |
refer to this object instead of *exporter* (See :ref:`Buffer Object Structures <buffer-structs>`). |
| 469 |
|
| 470 |
Successful calls to :c:func:`PyObject_GetBuffer` must be paired with calls |
| 471 |
to :c:func:`PyBuffer_Release`, similar to :c:func:`malloc` and :c:func:`free`. |
| 472 |
Thus, after the consumer is done with the buffer, :c:func:`PyBuffer_Release` |
| 473 |
must be called exactly once. |
| 474 |
|
| 475 |
|
| 476 |
.. c:function:: void PyBuffer_Release(Py_buffer *view) |
| 477 |
|
| 478 |
Release the buffer *view* and release the :term:`strong reference` |
| 479 |
(i.e. decrement the reference count) to the view's supporting object, |
| 480 |
``view->obj``. This function MUST be called when the buffer |
| 481 |
is no longer being used, otherwise reference leaks may occur. |
| 482 |
|
| 483 |
It is an error to call this function on a buffer that was not obtained via |
| 484 |
:c:func:`PyObject_GetBuffer`. |
| 485 |
|
| 486 |
|
| 487 |
.. c:function:: Py_ssize_t PyBuffer_SizeFromFormat(const char *format) |
| 488 |
|
| 489 |
Return the implied :c:member:`~Py_buffer.itemsize` from :c:member:`~Py_buffer.format`. |
| 490 |
On error, raise an exception and return -1. |
| 491 |
|
| 492 |
.. versionadded:: 3.9 |
| 493 |
|
| 494 |
|
| 495 |
.. c:function:: int PyBuffer_IsContiguous(const Py_buffer *view, char order) |
| 496 |
|
| 497 |
Return ``1`` if the memory defined by the *view* is C-style (*order* is |
| 498 |
``'C'``) or Fortran-style (*order* is ``'F'``) :term:`contiguous` or either one |
| 499 |
(*order* is ``'A'``). Return ``0`` otherwise. This function always succeeds. |
| 500 |
|
| 501 |
|
| 502 |
.. c:function:: void* PyBuffer_GetPointer(const Py_buffer *view, const Py_ssize_t *indices) |
| 503 |
|
| 504 |
Get the memory area pointed to by the *indices* inside the given *view*. |
| 505 |
*indices* must point to an array of ``view->ndim`` indices. |
| 506 |
|
| 507 |
|
| 508 |
.. c:function:: int PyBuffer_FromContiguous(const Py_buffer *view, const void *buf, Py_ssize_t len, char fort) |
| 509 |
|
| 510 |
Copy contiguous *len* bytes from *buf* to *view*. |
| 511 |
*fort* can be ``'C'`` or ``'F'`` (for C-style or Fortran-style ordering). |
| 512 |
``0`` is returned on success, ``-1`` on error. |
| 513 |
|
| 514 |
|
| 515 |
.. c:function:: int PyBuffer_ToContiguous(void *buf, const Py_buffer *src, Py_ssize_t len, char order) |
| 516 |
|
| 517 |
Copy *len* bytes from *src* to its contiguous representation in *buf*. |
| 518 |
*order* can be ``'C'`` or ``'F'`` or ``'A'`` (for C-style or Fortran-style |
| 519 |
ordering or either one). ``0`` is returned on success, ``-1`` on error. |
| 520 |
|
| 521 |
This function fails if *len* != *src->len*. |
| 522 |
|
| 523 |
|
| 524 |
.. c:function:: int PyObject_CopyData(PyObject *dest, PyObject *src) |
| 525 |
|
| 526 |
Copy data from *src* to *dest* buffer. Can convert between C-style and |
| 527 |
or Fortran-style buffers. |
| 528 |
|
| 529 |
``0`` is returned on success, ``-1`` on error. |
| 530 |
|
| 531 |
.. c:function:: void PyBuffer_FillContiguousStrides(int ndims, Py_ssize_t *shape, Py_ssize_t *strides, int itemsize, char order) |
| 532 |
|
| 533 |
Fill the *strides* array with byte-strides of a :term:`contiguous` (C-style if |
| 534 |
*order* is ``'C'`` or Fortran-style if *order* is ``'F'``) array of the |
| 535 |
given shape with the given number of bytes per element. |
| 536 |
|
| 537 |
|
| 538 |
.. c:function:: int PyBuffer_FillInfo(Py_buffer *view, PyObject *exporter, void *buf, Py_ssize_t len, int readonly, int flags) |
| 539 |
|
| 540 |
Handle buffer requests for an exporter that wants to expose *buf* of size *len* |
| 541 |
with writability set according to *readonly*. *buf* is interpreted as a sequence |
| 542 |
of unsigned bytes. |
| 543 |
|
| 544 |
The *flags* argument indicates the request type. This function always fills in |
| 545 |
*view* as specified by flags, unless *buf* has been designated as read-only |
| 546 |
and :c:macro:`PyBUF_WRITABLE` is set in *flags*. |
| 547 |
|
| 548 |
On success, set ``view->obj`` to a new reference to *exporter* and |
| 549 |
return 0. Otherwise, raise :exc:`BufferError`, set |
| 550 |
``view->obj`` to ``NULL`` and return ``-1``; |
| 551 |
|
| 552 |
If this function is used as part of a :ref:`getbufferproc <buffer-structs>`, |
| 553 |
*exporter* MUST be set to the exporting object and *flags* must be passed |
| 554 |
unmodified. Otherwise, *exporter* MUST be ``NULL``. |