c
single: buffer protocol single: buffer interface; (see buffer protocol) single: buffer object; (see buffer protocol)
Greg Stein <gstein@lyra.org>
Benjamin Peterson
Stefan Krah
Certain objects available in Python wrap access to an underlying memory array or buffer. Such objects include the built-in bytes
and bytearray
, and some extension types like array.array
. Third-party libraries may define their own types for special purposes, such as image processing or numeric analysis.
While each of these types have their own semantics, they share the common characteristic of being backed by a possibly large memory buffer. It is then desirable, in some situations, to access that buffer directly and without intermediate copying.
Python provides such a facility at the C level in the form of the buffer
protocol <bufferobjects>
. This protocol has two sides:
single: PyBufferProcs
- on the producer side, a type can export a "buffer interface" which allows objects of that type to expose information about their underlying buffer. This interface is described in the section
buffer-structs
; - on the consumer side, several means are available to obtain a pointer to the raw underlying data of an object (for example a method parameter).
Simple objects such as bytes
and bytearray
expose their underlying buffer in byte-oriented form. Other forms are possible; for example, the elements exposed by a array.array
can be multi-byte values.
An example consumer of the buffer interface is the ~io.BufferedIOBase.write
method of file objects: any object that can export a series of bytes through the buffer interface can be written to a file. While write
only needs read-only access to the internal contents of the object passed to it, other methods such as ~io.BufferedIOBase.readinto
need write access to the contents of their argument. The buffer interface allows objects to selectively allow or reject exporting of read-write and read-only buffers.
There are two ways for a consumer of the buffer interface to acquire a buffer over a target object:
- call :c
PyObject_GetBuffer
with the right parameters; - call :c
PyArg_ParseTuple
(or one of its siblings) with one of they*
,w*
ors*
format codes <arg-parsing>
.
In both cases, :cPyBuffer_Release
must be called when the buffer isn't needed anymore. Failure to do so could lead to various issues such as resource leaks.
Buffer structures (or simply "buffers") are useful as a way to expose the binary data from another object to the Python programmer. They can also be used as a zero-copy slicing mechanism. Using their ability to reference a block of memory, it is possible to expose any data to the Python programmer quite easily. The memory could be a large, constant array in a C extension, it could be a raw block of memory for manipulation before passing to an operating system library, or it could be used to pass around structured data in its native, in-memory format.
Contrary to most data types exposed by the Python interpreter, buffers are not :cPyObject
pointers but rather simple C structures. This allows them to be created and copied very simply. When a generic wrapper around a buffer is needed, a memoryview <memoryview-objects>
object can be created.
For short instructions how to write an exporting object, see Buffer Object Structures <buffer-structs>
. For obtaining a buffer, see :cPyObject_GetBuffer
.
Buffers are usually obtained by sending a buffer request to an exporting object via :cPyObject_GetBuffer
. Since the complexity of the logical structure of the memory can vary drastically, the consumer uses the flags argument to specify the exact buffer type it can handle.
All :cPy_buffer
fields are unambiguously defined by the request type.
The following fields are not influenced by flags and must always be filled in with the correct values: :c~Py_buffer.obj
, :c~Py_buffer.buf
, :c~Py_buffer.len
, :c~Py_buffer.itemsize
, :c~Py_buffer.ndim
.
:cPyBUF_WRITABLE
can be |'d to any of the flags in the next section. Since :cPyBUF_SIMPLE
is defined as 0, :cPyBUF_WRITABLE
can be used as a stand-alone flag to request a simple writable buffer.
:cPyBUF_FORMAT
can be |'d to any of the flags except :cPyBUF_SIMPLE
. The latter already implies format B
(unsigned bytes).
The flags that control the logical structure of the memory are listed in decreasing order of complexity. Note that each flag contains all bits of the flags below it.
Request | shape | strides | suboffsets |
---|---|---|---|
|
|
if needed | |
|
|
|
|
|
|
|
|
|
|
|
C or Fortran contiguity can be explicitly requested, with and without stride information. Without stride information, the buffer must be C-contiguous.
Request | shape | strides | suboffsets | contig |
---|---|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
C or F | |
|
|
|
|
All possible requests are fully defined by some combination of the flags in the previous section. For convenience, the buffer protocol provides frequently used combinations as single flags.
In the following table U stands for undefined contiguity. The consumer would have to call :cPyBuffer_IsContiguous
to determine contiguity.
Request | shape | strides | suboffsets | contig | readonly | format |
---|---|---|---|---|---|---|
|
|
if needed |
|
|
|
|
|
|
if needed |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
The logical structure of NumPy-style arrays is defined by :c~Py_buffer.itemsize
, :c~Py_buffer.ndim
, :c~Py_buffer.shape
and :c~Py_buffer.strides
.
If ndim == 0
, the memory location pointed to by :c~Py_buffer.buf
is interpreted as a scalar of size :c~Py_buffer.itemsize
. In that case, both :c~Py_buffer.shape
and :c~Py_buffer.strides
are NULL.
If :c~Py_buffer.strides
is NULL, the array is interpreted as a standard n-dimensional C-array. Otherwise, the consumer must access an n-dimensional array as follows:
ptr = (char *)buf + indices[0] * strides[0] + ... + indices[n-1] * strides[n-1]
item = *((typeof(item) *)ptr);
As noted above, :c~Py_buffer.buf
can point to any location within the actual memory block. An exporter can check the validity of a buffer with this function:
def verify_structure(memlen, itemsize, ndim, shape, strides, offset):
"""Verify that the parameters represent a valid array within
the bounds of the allocated memory:
char *mem: start of the physical memory block
memlen: length of the physical memory block
offset: (char *)buf - mem
"""
if offset % itemsize:
return False
if offset < 0 or offset+itemsize > memlen:
return False
if any(v % itemsize for v in strides):
return False
if ndim <= 0:
return ndim == 0 and not shape and not strides
if 0 in shape:
return True
imin = sum(strides[j]*(shape[j]-1) for j in range(ndim)
if strides[j] <= 0)
imax = sum(strides[j]*(shape[j]-1) for j in range(ndim)
if strides[j] > 0)
return 0 <= offset+imin and offset+imax+itemsize <= memlen
In addition to the regular items, PIL-style arrays can contain pointers that must be followed in order to get to the next element in a dimension. For example, the regular three-dimensional C-array char v[2][2][3]
can also be viewed as an array of 2 pointers to 2 two-dimensional arrays: char (*v[2])[2][3]
. In suboffsets representation, those two pointers can be embedded at the start of :c~Py_buffer.buf
, pointing to two char x[2][3]
arrays that can be located anywhere in memory.
Here is a function that returns a pointer to the element in an N-D array pointed to by an N-dimensional index when there are both non-NULL strides and suboffsets:
void *get_item_pointer(int ndim, void *buf, Py_ssize_t *strides,
Py_ssize_t *suboffsets, Py_ssize_t *indices) {
char *pointer = (char*)buf;
int i;
for (i = 0; i < ndim; i++) {
pointer += strides[i] * indices[i];
if (suboffsets[i] >=0 ) {
pointer = *((char**)pointer) + suboffsets[i];
}
}
return (void*)pointer;
}