Protocole tampon

Certains objets Python enveloppent l’accès à un tableau de mémoire sous-jacente (nommée zone tampon ou simplement tampon, buffer en anglais). Les objets natifs bytes et bytearray en sont des exemples, ainsi que quelques types d’extension comme array.array. Les bibliothèques tierces peuvent définir leurs propres types à des fins spéciales, telles que le traitement d’image ou l’analyse numérique.

Alors que chacun de ces types a sa propre sémantique, ils partagent la caractéristique commune d’être soutenus par un tampon de mémoire important. Il est donc souhaitable, dans certains cas, d’accéder à cette mémoire directement sans l’étape intermédiaire de copie.

Python fournit une telle facilité au niveau du C sous la forme de protocole tampon. Ce protocole comporte deux aspects :

  • du côté producteur, un type peut exporter une « interface tampon » qui permet aux objets de ce type d’exposer des informations concernant leur tampon sous-jacent. Cette interface est décrite dans la section Buffer Object Structures ;
  • du côté consommateur, plusieurs moyens sont disponibles pour obtenir un pointeur vers les données sous-jacentes brutes d’un objet (par exemple un paramètre de méthode).

Des objets simples tels que bytes et bytearray exposent leur tampon sous-jacent dans un format orienté octet. D’autres formes sont possibles ; par exemple, les éléments exposés par un array.array peuvent être des valeurs multi-octets.

Un exemple de consommateur de l’interface tampon est la méthode write() des objets fichiers : tout objet qui peut exporter une série d’octets à travers l’interface tampon peut être écrit dans un fichier. Alors que write() n’a besoin que d’un accès lecture au contenu interne de l’objet qui lui est passé, d’autres méthodes telles que readinto() nécessitent un accès écriture au contenu de leur argument. L’interface buffer permet aux objets d’autoriser ou de rejeter sélectivement l’exportation de tampons en mode lecture-écriture et en mode lecture seule.

Un consommateur de l’interface tampon peut acquérir un tampon sur un objet cible de deux manières :

Dans les deux cas, PyBuffer_Release() doit être appelée quand le tampon n’est plus nécessaire. Ne pas le faire peut conduire à divers problèmes tels que des fuites de ressources.

La structure buffer

Les structures tampons (ou simplement les « tampons », buffers en anglais) sont utiles pour exposer les données binaires d’un autre objet au programmeur Python. Elles peuvent également être utilisées comme un mécanisme de découpage sans copie. En utilisant leur capacité à référencer un bloc de mémoire, il est possible d’exposer toutes les données au programmeur Python assez facilement. La mémoire peut être un grand tableau constant dans une extension C, il peut s’agir d’un bloc brut de mémoire à manipuler avant de passer à une bibliothèque de système d’exploitation ou être utilisé pour transmettre des données structurées dans son format natif en mémoire.

Contrairement à la plupart des types de données exposés par l’interpréteur Python, les tampons ne sont pas de simples pointeurs vers PyObject mais plutôt des structures C simples. Cela leur permet d’être créés et copiés très simplement. lorsque vous avez besoin d’une enveloppe générique (wrapper en anglais) pour un tampon, un objet memoryview peut être créé.

For short instructions how to write an exporting object, see Buffer Object Structures. For obtaining a buffer, see PyObject_GetBuffer().

Py_buffer
void *buf

A pointer to the start of the logical structure described by the buffer fields. This can be any location within the underlying physical memory block of the exporter. For example, with negative strides the value may point to the end of the memory block.

For contiguous arrays, the value points to the beginning of the memory block.

void *obj

A new reference to the exporting object. The reference is owned by the consumer and automatically decremented and set to NULL by PyBuffer_Release(). The field is the equivalent of the return value of any standard C-API function.

As a special case, for temporary buffers that are wrapped by PyMemoryView_FromBuffer() or PyBuffer_FillInfo() this field is NULL. In general, exporting objects MUST NOT use this scheme.

Py_ssize_t len

product(shape) * itemsize. For contiguous arrays, this is the length of the underlying memory block. For non-contiguous arrays, it is the length that the logical structure would have if it were copied to a contiguous representation.

Accessing ((char *)buf)[0] up to ((char *)buf)[len-1] is only valid if the buffer has been obtained by a request that guarantees contiguity. In most cases such a request will be PyBUF_SIMPLE or PyBUF_WRITABLE.

int readonly

An indicator of whether the buffer is read-only. This field is controlled by the PyBUF_WRITABLE flag.

Py_ssize_t itemsize

Item size in bytes of a single element. Same as the value of struct.calcsize() called on non-NULL format values.

Important exception: If a consumer requests a buffer without the PyBUF_FORMAT flag, format will be set to NULL, but itemsize still has the value for the original format.

If shape is present, the equality product(shape) * itemsize == len still holds and the consumer can use itemsize to navigate the buffer.

If shape is NULL as a result of a PyBUF_SIMPLE or a PyBUF_WRITABLE request, the consumer must disregard itemsize and assume itemsize == 1.

const char *format

A NUL terminated string in struct module style syntax describing the contents of a single item. If this is NULL, "B" (unsigned bytes) is assumed.

This field is controlled by the PyBUF_FORMAT flag.

int ndim

The number of dimensions the memory represents as an n-dimensional array. If it is 0, buf points to a single item representing a scalar. In this case, shape, strides and suboffsets MUST be NULL.

The macro PyBUF_MAX_NDIM limits the maximum number of dimensions to 64. Exporters MUST respect this limit, consumers of multi-dimensional buffers SHOULD be able to handle up to PyBUF_MAX_NDIM dimensions.

Py_ssize_t *shape

An array of Py_ssize_t of length ndim indicating the shape of the memory as an n-dimensional array. Note that shape[0] * ... * shape[ndim-1] * itemsize MUST be equal to len.

Shape values are restricted to shape[n] >= 0. The case shape[n] == 0 requires special attention. See complex arrays for further information.

The shape array is read-only for the consumer.

Py_ssize_t *strides

An array of Py_ssize_t of length ndim giving the number of bytes to skip to get to a new element in each dimension.

Stride values can be any integer. For regular arrays, strides are usually positive, but a consumer MUST be able to handle the case strides[n] <= 0. See complex arrays for further information.

The strides array is read-only for the consumer.

Py_ssize_t *suboffsets

An array of Py_ssize_t of length ndim. If suboffsets[n] >= 0, the values stored along the nth dimension are pointers and the suboffset value dictates how many bytes to add to each pointer after de-referencing. A suboffset value that is negative indicates that no de-referencing should occur (striding in a contiguous memory block).

If all suboffsets are negative (i.e. no de-referencing is needed, then this field must be NULL (the default value).

This type of array representation is used by the Python Imaging Library (PIL). See complex arrays for further information how to access elements of such an array.

The suboffsets array is read-only for the consumer.

void *internal

This is for use internally by the exporting object. For example, this might be re-cast as an integer by the exporter and used to store flags about whether or not the shape, strides, and suboffsets arrays must be freed when the buffer is released. The consumer MUST NOT alter this value.

Buffer request types

Buffers are usually obtained by sending a buffer request to an exporting object via PyObject_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 Py_buffer fields are unambiguously defined by the request type.

request-independent fields

The following fields are not influenced by flags and must always be filled in with the correct values: obj, buf, len, itemsize, ndim.

readonly, format

PyBUF_WRITABLE

Controls the readonly field. If set, the exporter MUST provide a writable buffer or else report failure. Otherwise, the exporter MAY provide either a read-only or writable buffer, but the choice MUST be consistent for all consumers.

PyBUF_FORMAT

Controls the format field. If set, this field MUST be filled in correctly. Otherwise, this field MUST be NULL.

PyBUF_WRITABLE can be |”d to any of the flags in the next section. Since PyBUF_SIMPLE is defined as 0, PyBUF_WRITABLE can be used as a stand-alone flag to request a simple writable buffer.

PyBUF_FORMAT can be |”d to any of the flags except PyBUF_SIMPLE. The latter already implies format B (unsigned bytes).

shape, strides, suboffsets

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
PyBUF_INDIRECT
oui oui if needed
PyBUF_STRIDES
oui oui NULL
PyBUF_ND
oui NULL NULL
PyBUF_SIMPLE
NULL NULL NULL

contiguity requests

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
PyBUF_C_CONTIGUOUS
oui oui NULL C
PyBUF_F_CONTIGUOUS
oui oui NULL F
PyBUF_ANY_CONTIGUOUS
oui oui NULL C or F
PyBUF_ND
oui NULL NULL C

compound requests

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 PyBuffer_IsContiguous() to determine contiguity.

Request shape strides suboffsets contig readonly format
PyBUF_FULL
oui oui if needed U 0 oui
PyBUF_FULL_RO
oui oui if needed U 1 or 0 oui
PyBUF_RECORDS
oui oui NULL U 0 oui
PyBUF_RECORDS_RO
oui oui NULL U 1 or 0 oui
PyBUF_STRIDED
oui oui NULL U 0 NULL
PyBUF_STRIDED_RO
oui oui NULL U 1 or 0 NULL
PyBUF_CONTIG
oui NULL NULL C 0 NULL
PyBUF_CONTIG_RO
oui NULL NULL C 1 or 0 NULL

Complex arrays

NumPy-style: shape and strides

The logical structure of NumPy-style arrays is defined by itemsize, ndim, shape and strides.

If ndim == 0, the memory location pointed to by buf is interpreted as a scalar of size itemsize. In that case, both shape and strides are NULL.

If 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, 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

PIL-style: shape, strides and suboffsets

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 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;
}