ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
### 导航 - [索引](../genindex.xhtml "总目录") - [模块](../py-modindex.xhtml "Python 模块索引") | - [下一页](objbuffer.xhtml "Old Buffer Protocol") | - [上一页](iter.xhtml "迭代器协议") | - ![](https://box.kancloud.cn/a721fc7ec672275e257bbbfde49a4d4e_16x16.png) - [Python](https://www.python.org/) » - zh\_CN 3.7.3 [文档](../index.xhtml) » - [Python/C API 参考手册](index.xhtml) » - [抽象对象层](abstract.xhtml) » - $('.inline-search').show(0); | # 缓冲协议 在 Python 中可使用一些对象来包装对底层内存数组或称 *缓冲* 的访问。此类对象包括内置的 [`bytes`](../library/stdtypes.xhtml#bytes "bytes") 和 [`bytearray`](../library/stdtypes.xhtml#bytearray "bytearray") 以及一些如 [`array.array`](../library/array.xhtml#array.array "array.array") 这样的扩展类型。第三方库也可能会为了特殊的目的而定义它们自己的类型,例如用于图像处理和数值分析等。 虽然这些类型中的每一种都有自己的语义,但它们具有由可能较大的内存缓冲区支持的共同特征。 在某些情况下,希望直接访问该缓冲区而无需中间复制。 Python 以 [缓冲协议](#bufferobjects) 的形式在 C 层级上提供这样的功能。 此协议包括两个方面: - 在生产者这一方面,该类型的协议可以导出一个“缓冲区接口”,允许公开它的底层缓冲区信息。该接口的描述信息在 [Buffer Object Structures](typeobj.xhtml#buffer-structs) 一节中; - 在消费者一侧,有几种方法可用于获得指向对象的原始底层数据的指针(例如一个方法的形参)。 一些简单的对象例如 [`bytes`](../library/stdtypes.xhtml#bytes "bytes") 和 [`bytearray`](../library/stdtypes.xhtml#bytearray "bytearray") 会以面向字节的形式公开它们的底层缓冲区。 也可能会用其他形式;例如 [`array.array`](../library/array.xhtml#array.array "array.array") 所公开的元素可以是多字节值。 An example consumer of the buffer interface is the [`write()`](../library/io.xhtml#io.BufferedIOBase.write "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 [`readinto()`](../library/io.xhtml#io.BufferedIOBase.readinto "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 [`PyObject_GetBuffer()`](#c.PyObject_GetBuffer "PyObject_GetBuffer") with the right parameters; - call [`PyArg_ParseTuple()`](arg.xhtml#c.PyArg_ParseTuple "PyArg_ParseTuple") (or one of its siblings) with one of the `y*`, `w*` or `s*` [format codes](arg.xhtml#arg-parsing). In both cases, [`PyBuffer_Release()`](#c.PyBuffer_Release "PyBuffer_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 structure 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 [`PyObject`](structures.xhtml#c.PyObject "PyObject") 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.xhtml#memoryview-objects) object can be created. For short instructions how to write an exporting object, see [Buffer Object Structures](typeobj.xhtml#buffer-structs). For obtaining a buffer, see [`PyObject_GetBuffer()`](#c.PyObject_GetBuffer "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`](#c.Py_buffer.strides "Py_buffer.strides")the value may point to the end of the memory block. For [contiguous](../glossary.xhtml#term-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()`](#c.PyBuffer_Release "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()`](memoryview.xhtml#c.PyMemoryView_FromBuffer "PyMemoryView_FromBuffer") or [`PyBuffer_FillInfo()`](#c.PyBuffer_FillInfo "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`](#c.PyBUF_SIMPLE "PyBUF_SIMPLE") or [`PyBUF_WRITABLE`](#c.PyBUF_WRITABLE "PyBUF_WRITABLE"). int `readonly`An indicator of whether the buffer is read-only. This field is controlled by the [`PyBUF_WRITABLE`](#c.PyBUF_WRITABLE "PyBUF_WRITABLE") flag. Py\_ssize\_t `itemsize`Item size in bytes of a single element. Same as the value of [`struct.calcsize()`](../library/struct.xhtml#struct.calcsize "struct.calcsize")called on non-NULL [`format`](#c.Py_buffer.format "Py_buffer.format") values. Important exception: If a consumer requests a buffer without the [`PyBUF_FORMAT`](#c.PyBUF_FORMAT "PyBUF_FORMAT") flag, [`format`](#c.Py_buffer.format "Py_buffer.format") will be set to *NULL*, but [`itemsize`](#c.Py_buffer.itemsize "Py_buffer.itemsize") still has the value for the original format. If [`shape`](#c.Py_buffer.shape "Py_buffer.shape") is present, the equality `product(shape) * itemsize == len` still holds and the consumer can use [`itemsize`](#c.Py_buffer.itemsize "Py_buffer.itemsize") to navigate the buffer. If [`shape`](#c.Py_buffer.shape "Py_buffer.shape") is *NULL* as a result of a [`PyBUF_SIMPLE`](#c.PyBUF_SIMPLE "PyBUF_SIMPLE")or a [`PyBUF_WRITABLE`](#c.PyBUF_WRITABLE "PyBUF_WRITABLE") request, the consumer must disregard [`itemsize`](#c.Py_buffer.itemsize "Py_buffer.itemsize") and assume `itemsize == 1`. const char \*`format`A *NUL* terminated string in [`struct`](../library/struct.xhtml#module-struct "struct: Interpret bytes as packed binary data.") 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`](#c.PyBUF_FORMAT "PyBUF_FORMAT") flag. int `ndim`The number of dimensions the memory represents as an n-dimensional array. If it is `0`, [`buf`](#c.Py_buffer.buf "Py_buffer.buf") points to a single item representing a scalar. In this case, [`shape`](#c.Py_buffer.shape "Py_buffer.shape"), [`strides`](#c.Py_buffer.strides "Py_buffer.strides")and [`suboffsets`](#c.Py_buffer.suboffsets "Py_buffer.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`](#c.Py_buffer.ndim "Py_buffer.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`](#c.Py_buffer.len "Py_buffer.len"). Shape values are restricted to `shape[n] >= 0`. The case `shape[n] == 0` requires special attention. See [complex arrays](#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`](#c.Py_buffer.ndim "Py_buffer.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](#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`](#c.Py_buffer.ndim "Py_buffer.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](#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()`](#c.PyObject_GetBuffer "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`](#c.Py_buffer "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`](#c.Py_buffer.obj "Py_buffer.obj"), [`buf`](#c.Py_buffer.buf "Py_buffer.buf"), [`len`](#c.Py_buffer.len "Py_buffer.len"), [`itemsize`](#c.Py_buffer.itemsize "Py_buffer.itemsize"), [`ndim`](#c.Py_buffer.ndim "Py_buffer.ndim"). ### readonly, format > `PyBUF_WRITABLE`Controls the [`readonly`](#c.Py_buffer.readonly "Py_buffer.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`](#c.Py_buffer.format "Py_buffer.format") field. If set, this field MUST be filled in correctly. Otherwise, this field MUST be *NULL*. [`PyBUF_WRITABLE`](#c.PyBUF_WRITABLE "PyBUF_WRITABLE") can be |'d to any of the flags in the next section. Since [`PyBUF_SIMPLE`](#c.PyBUF_SIMPLE "PyBUF_SIMPLE") is defined as 0, [`PyBUF_WRITABLE`](#c.PyBUF_WRITABLE "PyBUF_WRITABLE")can be used as a stand-alone flag to request a simple writable buffer. [`PyBUF_FORMAT`](#c.PyBUF_FORMAT "PyBUF_FORMAT") can be |'d to any of the flags except [`PyBUF_SIMPLE`](#c.PyBUF_SIMPLE "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. 请求 shape strides suboffsets `PyBUF_INDIRECT`yes yes 如果需要的话 `PyBUF_STRIDES`yes yes NULL `PyBUF_ND`yes NULL NULL `PyBUF_SIMPLE`NULL NULL NULL ### 连续性的请求 C or Fortran [contiguity](../glossary.xhtml#term-contiguous) can be explicitly requested, with and without stride information. Without stride information, the buffer must be C-contiguous. 请求 shape strides suboffsets contig `PyBUF_C_CONTIGUOUS`yes yes NULL C `PyBUF_F_CONTIGUOUS`yes yes NULL F `PyBUF_ANY_CONTIGUOUS`yes yes NULL C 或 F `PyBUF_ND`yes 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()`](#c.PyBuffer_IsContiguous "PyBuffer_IsContiguous") to determine contiguity. 请求 shape strides suboffsets contig 只读 格式 `PyBUF_FULL`yes yes 如果需要的话 U 0 yes `PyBUF_FULL_RO`yes yes 如果需要的话 U 1 或 0 yes `PyBUF_RECORDS`yes yes NULL U 0 yes `PyBUF_RECORDS_RO`yes yes NULL U 1 或 0 yes `PyBUF_STRIDED`yes yes NULL U 0 NULL `PyBUF_STRIDED_RO`yes yes NULL U 1 或 0 NULL `PyBUF_CONTIG`yes NULL NULL C 0 NULL `PyBUF_CONTIG_RO`yes NULL NULL C 1 或 0 NULL ## 复杂数组 ### NumPy-style: shape and strides The logical structure of NumPy-style arrays is defined by [`itemsize`](#c.Py_buffer.itemsize "Py_buffer.itemsize"), [`ndim`](#c.Py_buffer.ndim "Py_buffer.ndim"), [`shape`](#c.Py_buffer.shape "Py_buffer.shape") and [`strides`](#c.Py_buffer.strides "Py_buffer.strides"). If `ndim == 0`, the memory location pointed to by [`buf`](#c.Py_buffer.buf "Py_buffer.buf") is interpreted as a scalar of size [`itemsize`](#c.Py_buffer.itemsize "Py_buffer.itemsize"). In that case, both [`shape`](#c.Py_buffer.shape "Py_buffer.shape") and [`strides`](#c.Py_buffer.strides "Py_buffer.strides") are *NULL*. If [`strides`](#c.Py_buffer.strides "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, [`buf`](#c.Py_buffer.buf "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 ``` ### 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`](#c.Py_buffer.buf "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; } ``` ## Buffer-related functions int `PyObject_CheckBuffer`([PyObject](structures.xhtml#c.PyObject "PyObject") *\*obj*)Return `1` if *obj* supports the buffer interface otherwise `0`. When `1` is returned, it doesn't guarantee that [`PyObject_GetBuffer()`](#c.PyObject_GetBuffer "PyObject_GetBuffer") will succeed. This function always succeeds. int `PyObject_GetBuffer`([PyObject](structures.xhtml#c.PyObject "PyObject") *\*exporter*, [Py\_buffer](#c.Py_buffer "Py_buffer") *\*view*, int *flags*)Send a request to *exporter* to fill in *view* as specified by *flags*. If the exporter cannot provide a buffer of the exact type, it MUST raise `PyExc_BufferError`, set `view->obj` to *NULL* and return `-1`. On success, fill in *view*, set `view->obj` to a new reference to *exporter* and return 0. In the case of chained buffer providers that redirect requests to a single object, `view->obj` MAY refer to this object instead of *exporter* (See [Buffer Object Structures](typeobj.xhtml#buffer-structs)). Successful calls to [`PyObject_GetBuffer()`](#c.PyObject_GetBuffer "PyObject_GetBuffer") must be paired with calls to [`PyBuffer_Release()`](#c.PyBuffer_Release "PyBuffer_Release"), similar to `malloc()` and `free()`. Thus, after the consumer is done with the buffer, [`PyBuffer_Release()`](#c.PyBuffer_Release "PyBuffer_Release")must be called exactly once. void `PyBuffer_Release`([Py\_buffer](#c.Py_buffer "Py_buffer") *\*view*)Release the buffer *view* and decrement the reference count for `view->obj`. This function MUST be called when the buffer is no longer being used, otherwise reference leaks may occur. It is an error to call this function on a buffer that was not obtained via [`PyObject_GetBuffer()`](#c.PyObject_GetBuffer "PyObject_GetBuffer"). Py\_ssize\_t `PyBuffer_SizeFromFormat`(const char *\**)Return the implied [`itemsize`](#c.Py_buffer.itemsize "Py_buffer.itemsize") from [`format`](#c.Py_buffer.format "Py_buffer.format"). This function is not yet implemented. int `PyBuffer_IsContiguous`([Py\_buffer](#c.Py_buffer "Py_buffer") *\*view*, char *order*)Return `1` if the memory defined by the *view* is C-style (*order* is `'C'`) or Fortran-style (*order* is `'F'`) [contiguous](../glossary.xhtml#term-contiguous) or either one (*order* is `'A'`). Return `0` otherwise. This function always succeeds. int `PyBuffer_ToContiguous`(void *\*buf*, [Py\_buffer](#c.Py_buffer "Py_buffer") *\*src*, Py\_ssize\_t *len*, char *order*)Copy *len* bytes from *src* to its contiguous representation in *buf*. *order* can be `'C'` or `'F'` (for C-style or Fortran-style ordering). `0` is returned on success, `-1` on error. This function fails if *len* != *src->len*. void `PyBuffer_FillContiguousStrides`(int *ndims*, Py\_ssize\_t *\*shape*, Py\_ssize\_t *\*strides*, int *itemsize*, char *order*)Fill the *strides* array with byte-strides of a [contiguous](../glossary.xhtml#term-contiguous) (C-style if *order* is `'C'` or Fortran-style if *order* is `'F'`) array of the given shape with the given number of bytes per element. int `PyBuffer_FillInfo`([Py\_buffer](#c.Py_buffer "Py_buffer") *\*view*, [PyObject](structures.xhtml#c.PyObject "PyObject") *\*exporter*, void *\*buf*, Py\_ssize\_t *len*, int *readonly*, int *flags*)Handle buffer requests for an exporter that wants to expose *buf* of size *len*with writability set according to *readonly*. *buf* is interpreted as a sequence of unsigned bytes. The *flags* argument indicates the request type. This function always fills in *view* as specified by flags, unless *buf* has been designated as read-only and [`PyBUF_WRITABLE`](#c.PyBUF_WRITABLE "PyBUF_WRITABLE") is set in *flags*. On success, set `view->obj` to a new reference to *exporter* and return 0. Otherwise, raise `PyExc_BufferError`, set `view->obj` to *NULL* and return `-1`; If this function is used as part of a [getbufferproc](typeobj.xhtml#buffer-structs), *exporter* MUST be set to the exporting object and *flags* must be passed unmodified. Otherwise, *exporter* MUST be NULL. ### 导航 - [索引](../genindex.xhtml "总目录") - [模块](../py-modindex.xhtml "Python 模块索引") | - [下一页](objbuffer.xhtml "Old Buffer Protocol") | - [上一页](iter.xhtml "迭代器协议") | - ![](https://box.kancloud.cn/a721fc7ec672275e257bbbfde49a4d4e_16x16.png) - [Python](https://www.python.org/) » - zh\_CN 3.7.3 [文档](../index.xhtml) » - [Python/C API 参考手册](index.xhtml) » - [抽象对象层](abstract.xhtml) » - $('.inline-search').show(0); | © [版权所有](../copyright.xhtml) 2001-2019, Python Software Foundation. Python 软件基金会是一个非盈利组织。 [请捐助。](https://www.python.org/psf/donations/) 最后更新于 5月 21, 2019. [发现了问题](../bugs.xhtml)? 使用[Sphinx](http://sphinx.pocoo.org/)1.8.4 创建。