8 .. sectionauthor:: Greg Stein <gstein@lyra.org>
9 .. sectionauthor:: Benjamin Peterson
13 single: buffer interface
15 Python objects implemented in C can export a "buffer interface." These
16 functions can be used by an object to expose its data in a raw, byte-oriented
17 format. Clients of the object can use the buffer interface to access the
18 object data directly, without needing to copy it first.
20 Two examples of objects that support the buffer interface are bytes and
21 arrays. The bytes object exposes the character contents in the buffer
22 interface's byte-oriented form. An array can also expose its contents, but it
23 should be noted that array elements may be multi-byte values.
25 An example user of the buffer interface is the file object's :meth:`write`
26 method. Any object that can export a series of bytes through the buffer
27 interface can be written to a file. There are a number of format codes to
28 :cfunc:`PyArg_ParseTuple` that operate against an object's buffer interface,
29 returning data from the target object.
31 .. index:: single: PyBufferProcs
33 More information on the buffer interface is provided in the section
34 :ref:`buffer-structs`, under the description for :ctype:`PyBufferProcs`.
36 Buffer objects are useful as a way to expose the data from another object's
37 buffer interface to the Python programmer. They can also be used as a zero-copy
38 slicing mechanism. Using their ability to reference a block of memory, it is
39 possible to expose any data to the Python programmer quite easily. The memory
40 could be a large, constant array in a C extension, it could be a raw block of
41 memory for manipulation before passing to an operating system library, or it
42 could be used to pass around structured data in its native, in-memory format.
47 .. cmember:: void *buf
49 A pointer to the start of the memory for the object.
51 .. cmember:: Py_ssize_t len
54 The total length of the memory in bytes.
56 .. cmember:: int readonly
58 An indicator of whether the buffer is read only.
60 .. cmember:: const char *format
63 A *NULL* terminated string in :mod:`struct` module style syntax giving
64 the contents of the elements available through the buffer. If this is
65 *NULL*, ``"B"`` (unsigned bytes) is assumed.
69 The number of dimensions the memory represents as a multi-dimensional
70 array. If it is 0, :cdata:`strides` and :cdata:`suboffsets` must be
73 .. cmember:: Py_ssize_t *shape
75 An array of :ctype:`Py_ssize_t`\s the length of :cdata:`ndim` giving the
76 shape of the memory as a multi-dimensional array. Note that
77 ``((*shape)[0] * ... * (*shape)[ndims-1])*itemsize`` should be equal to
80 .. cmember:: Py_ssize_t *strides
82 An array of :ctype:`Py_ssize_t`\s the length of :cdata:`ndim` giving the
83 number of bytes to skip to get to a new element in each dimension.
85 .. cmember:: Py_ssize_t *suboffsets
87 An array of :ctype:`Py_ssize_t`\s the length of :cdata:`ndim`. If these
88 suboffset numbers are greater than or equal to 0, then the value stored
89 along the indicated dimension is a pointer and the suboffset value
90 dictates how many bytes to add to the pointer after de-referencing. A
91 suboffset value that it negative indicates that no de-referencing should
92 occur (striding in a contiguous memory block).
94 Here is a function that returns a pointer to the element in an N-D array
95 pointed to by an N-dimensional index when there are both non-NULL strides
98 void *get_item_pointer(int ndim, void *buf, Py_ssize_t *strides,
99 Py_ssize_t *suboffsets, Py_ssize_t *indices) {
100 char *pointer = (char*)buf;
102 for (i = 0; i < ndim; i++) {
103 pointer += strides[i] * indices[i];
104 if (suboffsets[i] >=0 ) {
105 pointer = *((char**)pointer) + suboffsets[i];
108 return (void*)pointer;
112 .. cmember:: Py_ssize_t itemsize
114 This is a storage for the itemsize (in bytes) of each element of the
115 shared memory. It is technically un-necessary as it can be obtained
116 using :cfunc:`PyBuffer_SizeFromFormat`, however an exporter may know
117 this information without parsing the format string and it is necessary
118 to know the itemsize for proper interpretation of striding. Therefore,
119 storing it is more convenient and faster.
121 .. cmember:: void *internal
123 This is for use internally by the exporting object. For example, this
124 might be re-cast as an integer by the exporter and used to store flags
125 about whether or not the shape, strides, and suboffsets arrays must be
126 freed when the buffer is released. The consumer should never alter this
130 Buffer related functions
131 ========================
134 .. cfunction:: int PyObject_CheckBuffer(PyObject *obj)
136 Return 1 if *obj* supports the buffer interface otherwise 0.
139 .. cfunction:: int PyObject_GetBuffer(PyObject *obj, Py_buffer *view, int flags)
141 Export *obj* into a :ctype:`Py_buffer`, *view*. These arguments must
142 never be *NULL*. The *flags* argument is a bit field indicating what
143 kind of buffer the caller is prepared to deal with and therefore what
144 kind of buffer the exporter is allowed to return. The buffer interface
145 allows for complicated memory sharing possibilities, but some caller may
146 not be able to handle all the complexity but may want to see if the
147 exporter will let them take a simpler view to its memory.
149 Some exporters may not be able to share memory in every possible way and
150 may need to raise errors to signal to some consumers that something is
151 just not possible. These errors should be a :exc:`BufferError` unless
152 there is another error that is actually causing the problem. The
153 exporter can use flags information to simplify how much of the
154 :cdata:`Py_buffer` structure is filled in with non-default values and/or
155 raise an error if the object can't support a simpler view of its memory.
157 0 is returned on success and -1 on error.
159 The following table gives possible values to the *flags* arguments.
161 +------------------------------+---------------------------------------------------+
162 | Flag | Description |
163 +==============================+===================================================+
164 | :cmacro:`PyBUF_SIMPLE` | This is the default flag state. The returned |
165 | | buffer may or may not have writable memory. The |
166 | | format of the data will be assumed to be unsigned |
167 | | bytes. This is a "stand-alone" flag constant. It |
168 | | never needs to be '|'d to the others. The exporter|
169 | | will raise an error if it cannot provide such a |
170 | | contiguous buffer of bytes. |
172 +------------------------------+---------------------------------------------------+
173 | :cmacro:`PyBUF_WRITABLE` | The returned buffer must be writable. If it is |
174 | | not writable, then raise an error. |
175 +------------------------------+---------------------------------------------------+
176 | :cmacro:`PyBUF_STRIDES` | This implies :cmacro:`PyBUF_ND`. The returned |
177 | | buffer must provide strides information (i.e. the |
178 | | strides cannot be NULL). This would be used when |
179 | | the consumer can handle strided, discontiguous |
180 | | arrays. Handling strides automatically assumes |
181 | | you can handle shape. The exporter can raise an |
182 | | error if a strided representation of the data is |
183 | | not possible (i.e. without the suboffsets). |
185 +------------------------------+---------------------------------------------------+
186 | :cmacro:`PyBUF_ND` | The returned buffer must provide shape |
187 | | information. The memory will be assumed C-style |
188 | | contiguous (last dimension varies the |
189 | | fastest). The exporter may raise an error if it |
190 | | cannot provide this kind of contiguous buffer. If |
191 | | this is not given then shape will be *NULL*. |
195 +------------------------------+---------------------------------------------------+
196 |:cmacro:`PyBUF_C_CONTIGUOUS` | These flags indicate that the contiguity returned |
197 |:cmacro:`PyBUF_F_CONTIGUOUS` | buffer must be respectively, C-contiguous (last |
198 |:cmacro:`PyBUF_ANY_CONTIGUOUS`| dimension varies the fastest), Fortran contiguous |
199 | | (first dimension varies the fastest) or either |
200 | | one. All of these flags imply |
201 | | :cmacro:`PyBUF_STRIDES` and guarantee that the |
202 | | strides buffer info structure will be filled in |
205 +------------------------------+---------------------------------------------------+
206 | :cmacro:`PyBUF_INDIRECT` | This flag indicates the returned buffer must have |
207 | | suboffsets information (which can be NULL if no |
208 | | suboffsets are needed). This can be used when |
209 | | the consumer can handle indirect array |
210 | | referencing implied by these suboffsets. This |
211 | | implies :cmacro:`PyBUF_STRIDES`. |
215 +------------------------------+---------------------------------------------------+
216 | :cmacro:`PyBUF_FORMAT` | The returned buffer must have true format |
217 | | information if this flag is provided. This would |
218 | | be used when the consumer is going to be checking |
219 | | for what 'kind' of data is actually stored. An |
220 | | exporter should always be able to provide this |
221 | | information if requested. If format is not |
222 | | explicitly requested then the format must be |
223 | | returned as *NULL* (which means ``'B'``, or |
224 | | unsigned bytes) |
225 +------------------------------+---------------------------------------------------+
226 | :cmacro:`PyBUF_STRIDED` | This is equivalent to ``(PyBUF_STRIDES | |
227 | | PyBUF_WRITABLE)``. |
228 +------------------------------+---------------------------------------------------+
229 | :cmacro:`PyBUF_STRIDED_RO` | This is equivalent to ``(PyBUF_STRIDES)``. |
231 +------------------------------+---------------------------------------------------+
232 | :cmacro:`PyBUF_RECORDS` | This is equivalent to ``(PyBUF_STRIDES | |
233 | | PyBUF_FORMAT | PyBUF_WRITABLE)``. |
234 +------------------------------+---------------------------------------------------+
235 | :cmacro:`PyBUF_RECORDS_RO` | This is equivalent to ``(PyBUF_STRIDES | |
236 | | PyBUF_FORMAT)``. |
237 +------------------------------+---------------------------------------------------+
238 | :cmacro:`PyBUF_FULL` | This is equivalent to ``(PyBUF_INDIRECT | |
239 | | PyBUF_FORMAT | PyBUF_WRITABLE)``. |
240 +------------------------------+---------------------------------------------------+
241 | :cmacro:`PyBUF_FULL_RO` | This is equivalent to ``(PyBUF_INDIRECT | |
242 | | PyBUF_FORMAT)``. |
243 +------------------------------+---------------------------------------------------+
244 | :cmacro:`PyBUF_CONTIG` | This is equivalent to ``(PyBUF_ND | |
245 | | PyBUF_WRITABLE)``. |
246 +------------------------------+---------------------------------------------------+
247 | :cmacro:`PyBUF_CONTIG_RO` | This is equivalent to ``(PyBUF_ND)``. |
249 +------------------------------+---------------------------------------------------+
252 .. cfunction:: void PyBuffer_Release(PyObject *obj, Py_buffer *view)
254 Release the buffer *view* over *obj*. This should be called when the buffer
255 is no longer being used as it may free memory from it.
258 .. cfunction:: Py_ssize_t PyBuffer_SizeFromFormat(const char *)
260 Return the implied :cdata:`~Py_buffer.itemsize` from the struct-stype
261 :cdata:`~Py_buffer.format`.
264 .. cfunction:: int PyObject_CopyToObject(PyObject *obj, void *buf, Py_ssize_t len, char fortran)
266 Copy *len* bytes of data pointed to by the contiguous chunk of memory
267 pointed to by *buf* into the buffer exported by obj. The buffer must of
268 course be writable. Return 0 on success and return -1 and raise an error
269 on failure. If the object does not have a writable buffer, then an error
270 is raised. If *fortran* is ``'F'``, then if the object is
271 multi-dimensional, then the data will be copied into the array in
272 Fortran-style (first dimension varies the fastest). If *fortran* is
273 ``'C'``, then the data will be copied into the array in C-style (last
274 dimension varies the fastest). If *fortran* is ``'A'``, then it does not
275 matter and the copy will be made in whatever way is more efficient.
278 .. cfunction:: int PyBuffer_IsContiguous(Py_buffer *view, char fortran)
280 Return 1 if the memory defined by the *view* is C-style (*fortran* is
281 ``'C'``) or Fortran-style (*fortran* is ``'F'``) contiguous or either one
282 (*fortran* is ``'A'``). Return 0 otherwise.
285 .. cfunction:: void PyBuffer_FillContiguousStrides(int ndim, Py_ssize_t *shape, Py_ssize_t *strides, Py_ssize_t itemsize, char fortran)
287 Fill the *strides* array with byte-strides of a contiguous (C-style if
288 *fortran* is ``'C'`` or Fortran-style if *fortran* is ``'F'`` array of the
289 given shape with the given number of bytes per element.
292 .. cfunction:: int PyBuffer_FillInfo(Py_buffer *view, void *buf, Py_ssize_t len, int readonly, int infoflags)
294 Fill in a buffer-info structure, *view*, correctly for an exporter that can
295 only share a contiguous chunk of memory of "unsigned bytes" of the given
296 length. Return 0 on success and -1 (with raising an error) on error.
306 A memoryview object exposes the C level buffer interface to Python.
309 .. cfunction:: PyObject* PyMemoryView_FromObject(PyObject *obj)
311 Return a memoryview object from an object that defines the buffer interface.
314 .. cfunction:: PyObject * PyMemoryView_GetContiguous(PyObject *obj, int buffertype, char order)
316 Return a memoryview object to a contiguous chunk of memory (in either
317 'C' or 'F'ortran order) from an object that defines the buffer
318 interface. If memory is contiguous, the memoryview object points to the
319 original memory. Otherwise copy is made and the memoryview points to a