blob: 37866b7dbdc542344c7e74b2d2dbb163f0b5fad9 [file] [log] [blame]
Georg Brandl54a3faa2008-01-20 09:30:57 +00001.. highlightlang:: c
2
3.. _bufferobjects:
4
Antoine Pitroudebf4db2010-09-28 23:41:31 +00005Buffer Protocol
6---------------
Georg Brandl54a3faa2008-01-20 09:30:57 +00007
8.. sectionauthor:: Greg Stein <gstein@lyra.org>
Benjamin Peterson9d0ced32008-09-16 02:24:31 +00009.. sectionauthor:: Benjamin Peterson
Georg Brandl54a3faa2008-01-20 09:30:57 +000010
11
12.. index::
Georg Brandl54a3faa2008-01-20 09:30:57 +000013 single: buffer interface
14
Antoine Pitroua92d1f52010-12-12 21:07:49 +000015Certain objects available in Python wrap access to an underlying memory
16array or *buffer*. Such objects include the built-in :class:`bytes` and
17:class:`bytearray`, and some extension types like :class:`array.array`.
18Third-party libraries may define their own types for special purposes, such
19as image processing or numeric analysis.
Georg Brandl54a3faa2008-01-20 09:30:57 +000020
Antoine Pitroua92d1f52010-12-12 21:07:49 +000021While each of these types have their own semantics, they share the common
22characteristic of being backed by a possibly large memory buffer. It is
23then desireable, in some situations, to access that buffer directly and
24without intermediate copying.
25
26Python provides such a facility at the C level in the form of the *buffer
27protocol*. This protocol has two sides:
28
29.. index:: single: PyBufferProcs
30
31- on the producer side, a type can export a "buffer interface" which allows
32 objects of that type to expose information about their underlying buffer.
33 This interface is described in the section :ref:`buffer-structs`;
34
35- on the consumer side, several means are available to obtain a pointer to
36 the raw underlying data of an object (for example a method parameter).
37
38Simple objects such as :class:`bytes` and :class:`bytearray` expose their
39underlying buffer in byte-oriented form. Other forms are possible; for example,
40the elements exposed by a :class:`array.array` can be multi-byte values.
Georg Brandl54a3faa2008-01-20 09:30:57 +000041
Antoine Pitrou9207f1d2010-09-28 23:05:17 +000042An example consumer of the buffer interface is the :meth:`~io.BufferedIOBase.write`
43method of file objects: any object that can export a series of bytes through
44the buffer interface can be written to a file. While :meth:`write` only
45needs read-only access to the internal contents of the object passed to it,
46other methods such as :meth:`~io.BufferedIOBase.readinto` need write access
47to the contents of their argument. The buffer interface allows objects to
48selectively allow or reject exporting of read-write and read-only buffers.
49
50There are two ways for a consumer of the buffer interface to acquire a buffer
51over a target object:
52
53* call :cfunc:`PyObject_GetBuffer` with the right parameters;
54
55* call :cfunc:`PyArg_ParseTuple` (or one of its siblings) with one of the
56 ``y*``, ``w*`` or ``s*`` :ref:`format codes <arg-parsing>`.
57
58In both cases, :cfunc:`PyBuffer_Release` must be called when the buffer
59isn't needed anymore. Failure to do so could lead to various issues such as
60resource leaks.
61
Georg Brandl54a3faa2008-01-20 09:30:57 +000062
Antoine Pitroudebf4db2010-09-28 23:41:31 +000063The buffer structure
64====================
Antoine Pitrou9207f1d2010-09-28 23:05:17 +000065
Antoine Pitroudebf4db2010-09-28 23:41:31 +000066Buffer structures (or simply "buffers") are useful as a way to expose the
67binary data from another object to the Python programmer. They can also be
68used as a zero-copy slicing mechanism. Using their ability to reference a
69block of memory, it is possible to expose any data to the Python programmer
70quite easily. The memory could be a large, constant array in a C extension,
71it could be a raw block of memory for manipulation before passing to an
72operating system library, or it could be used to pass around structured data
73in its native, in-memory format.
Georg Brandl54a3faa2008-01-20 09:30:57 +000074
Antoine Pitroudebf4db2010-09-28 23:41:31 +000075Contrary to most data types exposed by the Python interpreter, buffers
Antoine Pitrou9207f1d2010-09-28 23:05:17 +000076are not :ctype:`PyObject` pointers but rather simple C structures. This
77allows them to be created and copied very simply. When a generic wrapper
Antoine Pitrou6ec5ed22010-09-29 00:01:41 +000078around a buffer is needed, a :ref:`memoryview <memoryview-objects>` object
Antoine Pitrou9207f1d2010-09-28 23:05:17 +000079can be created.
80
Georg Brandl54a3faa2008-01-20 09:30:57 +000081
Benjamin Peterson9d0ced32008-09-16 02:24:31 +000082.. ctype:: Py_buffer
Georg Brandl54a3faa2008-01-20 09:30:57 +000083
Benjamin Peterson9d0ced32008-09-16 02:24:31 +000084 .. cmember:: void *buf
85
86 A pointer to the start of the memory for the object.
87
88 .. cmember:: Py_ssize_t len
Benjamin Petersonf2fa87b2008-09-17 22:59:21 +000089 :noindex:
Benjamin Peterson9d0ced32008-09-16 02:24:31 +000090
91 The total length of the memory in bytes.
92
93 .. cmember:: int readonly
94
95 An indicator of whether the buffer is read only.
96
97 .. cmember:: const char *format
Benjamin Petersonf2fa87b2008-09-17 22:59:21 +000098 :noindex:
Benjamin Peterson9d0ced32008-09-16 02:24:31 +000099
Jeroen Ruigrok van der Wervenbd875522009-04-26 21:06:15 +0000100 A *NULL* terminated string in :mod:`struct` module style syntax giving
101 the contents of the elements available through the buffer. If this is
102 *NULL*, ``"B"`` (unsigned bytes) is assumed.
Benjamin Peterson9d0ced32008-09-16 02:24:31 +0000103
104 .. cmember:: int ndim
105
106 The number of dimensions the memory represents as a multi-dimensional
107 array. If it is 0, :cdata:`strides` and :cdata:`suboffsets` must be
108 *NULL*.
109
110 .. cmember:: Py_ssize_t *shape
111
112 An array of :ctype:`Py_ssize_t`\s the length of :cdata:`ndim` giving the
113 shape of the memory as a multi-dimensional array. Note that
114 ``((*shape)[0] * ... * (*shape)[ndims-1])*itemsize`` should be equal to
115 :cdata:`len`.
116
117 .. cmember:: Py_ssize_t *strides
118
119 An array of :ctype:`Py_ssize_t`\s the length of :cdata:`ndim` giving the
120 number of bytes to skip to get to a new element in each dimension.
121
122 .. cmember:: Py_ssize_t *suboffsets
123
124 An array of :ctype:`Py_ssize_t`\s the length of :cdata:`ndim`. If these
125 suboffset numbers are greater than or equal to 0, then the value stored
126 along the indicated dimension is a pointer and the suboffset value
127 dictates how many bytes to add to the pointer after de-referencing. A
128 suboffset value that it negative indicates that no de-referencing should
129 occur (striding in a contiguous memory block).
130
131 Here is a function that returns a pointer to the element in an N-D array
Georg Brandlae2dbe22009-03-13 19:04:40 +0000132 pointed to by an N-dimensional index when there are both non-NULL strides
Benjamin Peterson9d0ced32008-09-16 02:24:31 +0000133 and suboffsets::
134
135 void *get_item_pointer(int ndim, void *buf, Py_ssize_t *strides,
136 Py_ssize_t *suboffsets, Py_ssize_t *indices) {
137 char *pointer = (char*)buf;
138 int i;
139 for (i = 0; i < ndim; i++) {
140 pointer += strides[i] * indices[i];
141 if (suboffsets[i] >=0 ) {
142 pointer = *((char**)pointer) + suboffsets[i];
Georg Brandl48310cd2009-01-03 21:18:54 +0000143 }
Benjamin Peterson9d0ced32008-09-16 02:24:31 +0000144 }
145 return (void*)pointer;
146 }
Georg Brandl54a3faa2008-01-20 09:30:57 +0000147
148
Benjamin Peterson9d0ced32008-09-16 02:24:31 +0000149 .. cmember:: Py_ssize_t itemsize
Georg Brandl54a3faa2008-01-20 09:30:57 +0000150
Benjamin Peterson9d0ced32008-09-16 02:24:31 +0000151 This is a storage for the itemsize (in bytes) of each element of the
Jeroen Ruigrok van der Wervenbd875522009-04-26 21:06:15 +0000152 shared memory. It is technically un-necessary as it can be obtained
153 using :cfunc:`PyBuffer_SizeFromFormat`, however an exporter may know
154 this information without parsing the format string and it is necessary
155 to know the itemsize for proper interpretation of striding. Therefore,
156 storing it is more convenient and faster.
Georg Brandl54a3faa2008-01-20 09:30:57 +0000157
Benjamin Peterson9d0ced32008-09-16 02:24:31 +0000158 .. cmember:: void *internal
159
160 This is for use internally by the exporting object. For example, this
161 might be re-cast as an integer by the exporter and used to store flags
162 about whether or not the shape, strides, and suboffsets arrays must be
163 freed when the buffer is released. The consumer should never alter this
164 value.
Georg Brandl54a3faa2008-01-20 09:30:57 +0000165
166
Antoine Pitrou6ec5ed22010-09-29 00:01:41 +0000167Buffer-related functions
Benjamin Peterson9d0ced32008-09-16 02:24:31 +0000168========================
Georg Brandl54a3faa2008-01-20 09:30:57 +0000169
170
Benjamin Peterson9d0ced32008-09-16 02:24:31 +0000171.. cfunction:: int PyObject_CheckBuffer(PyObject *obj)
Georg Brandl54a3faa2008-01-20 09:30:57 +0000172
Antoine Pitrou9207f1d2010-09-28 23:05:17 +0000173 Return 1 if *obj* supports the buffer interface otherwise 0. When 1 is
174 returned, it doesn't guarantee that :cfunc:`PyObject_GetBuffer` will
175 succeed.
Georg Brandl54a3faa2008-01-20 09:30:57 +0000176
177
Benjamin Petersonfa0d7032009-06-01 22:42:33 +0000178.. cfunction:: int PyObject_GetBuffer(PyObject *obj, Py_buffer *view, int flags)
Georg Brandl54a3faa2008-01-20 09:30:57 +0000179
Antoine Pitrou9207f1d2010-09-28 23:05:17 +0000180 Export a view over some internal data from the target object *obj*.
181 *obj* must not be NULL, and *view* must point to an existing
182 :ctype:`Py_buffer` structure allocated by the caller (most uses of
183 this function will simply declare a local variable of type
184 :ctype:`Py_buffer`). The *flags* argument is a bit field indicating
185 what kind of buffer is requested. The buffer interface allows
186 for complicated memory layout possibilities; however, some callers
187 won't want to handle all the complexity and instead request a simple
188 view of the target object (using :cmacro:`PyBUF_SIMPLE` for a read-only
189 view and :cmacro:`PyBUF_WRITABLE` for a read-write view).
Benjamin Peterson9d0ced32008-09-16 02:24:31 +0000190
191 Some exporters may not be able to share memory in every possible way and
192 may need to raise errors to signal to some consumers that something is
193 just not possible. These errors should be a :exc:`BufferError` unless
Jeroen Ruigrok van der Wervenbd875522009-04-26 21:06:15 +0000194 there is another error that is actually causing the problem. The
195 exporter can use flags information to simplify how much of the
196 :cdata:`Py_buffer` structure is filled in with non-default values and/or
197 raise an error if the object can't support a simpler view of its memory.
Benjamin Peterson9d0ced32008-09-16 02:24:31 +0000198
Antoine Pitrou9207f1d2010-09-28 23:05:17 +0000199 On success, 0 is returned and the *view* structure is filled with useful
200 values. On error, -1 is returned and an exception is raised; the *view*
201 is left in an undefined state.
Benjamin Peterson9d0ced32008-09-16 02:24:31 +0000202
Georg Brandlc9e59c12010-10-01 05:41:48 +0000203 The following are the possible values to the *flags* arguments.
Benjamin Peterson9d0ced32008-09-16 02:24:31 +0000204
Georg Brandlc9e59c12010-10-01 05:41:48 +0000205 .. cmacro:: PyBUF_SIMPLE
206
207 This is the default flag. The returned buffer exposes a read-only
208 memory area. The format of data is assumed to be raw unsigned bytes,
209 without any particular structure. This is a "stand-alone" flag
210 constant. It never needs to be '|'d to the others. The exporter will
211 raise an error if it cannot provide such a contiguous buffer of bytes.
212
213 .. cmacro:: PyBUF_WRITABLE
214
215 Like :cmacro:`PyBUF_SIMPLE`, but the returned buffer is writable. If
216 the exporter doesn't support writable buffers, an error is raised.
217
218 .. cmacro:: PyBUF_STRIDES
219
220 This implies :cmacro:`PyBUF_ND`. The returned buffer must provide
221 strides information (i.e. the strides cannot be NULL). This would be
222 used when the consumer can handle strided, discontiguous arrays.
223 Handling strides automatically assumes you can handle shape. The
224 exporter can raise an error if a strided representation of the data is
225 not possible (i.e. without the suboffsets).
226
227 .. cmacro:: PyBUF_ND
228
229 The returned buffer must provide shape information. The memory will be
230 assumed C-style contiguous (last dimension varies the fastest). The
231 exporter may raise an error if it cannot provide this kind of
232 contiguous buffer. If this is not given then shape will be *NULL*.
233
234 .. cmacro:: PyBUF_C_CONTIGUOUS
Georg Brandl48a866c2010-10-06 06:49:22 +0000235
236 .. cmacro:: PyBUF_F_CONTIGUOUS
237
238 .. cmacro:: PyBUF_ANY_CONTIGUOUS
Georg Brandlc9e59c12010-10-01 05:41:48 +0000239
240 These flags indicate that the contiguity returned buffer must be
241 respectively, C-contiguous (last dimension varies the fastest), Fortran
242 contiguous (first dimension varies the fastest) or either one. All of
243 these flags imply :cmacro:`PyBUF_STRIDES` and guarantee that the
244 strides buffer info structure will be filled in correctly.
245
246 .. cmacro:: PyBUF_INDIRECT
247
248 This flag indicates the returned buffer must have suboffsets
249 information (which can be NULL if no suboffsets are needed). This can
250 be used when the consumer can handle indirect array referencing implied
251 by these suboffsets. This implies :cmacro:`PyBUF_STRIDES`.
252
253 .. cmacro:: PyBUF_FORMAT
254
255 The returned buffer must have true format information if this flag is
256 provided. This would be used when the consumer is going to be checking
257 for what 'kind' of data is actually stored. An exporter should always
258 be able to provide this information if requested. If format is not
259 explicitly requested then the format must be returned as *NULL* (which
260 means ``'B'``, or unsigned bytes).
261
262 .. cmacro:: PyBUF_STRIDED
263
264 This is equivalent to ``(PyBUF_STRIDES | PyBUF_WRITABLE)``.
265
266 .. cmacro:: PyBUF_STRIDED_RO
267
268 This is equivalent to ``(PyBUF_STRIDES)``.
269
270 .. cmacro:: PyBUF_RECORDS
271
272 This is equivalent to ``(PyBUF_STRIDES | PyBUF_FORMAT |
273 PyBUF_WRITABLE)``.
274
275 .. cmacro:: PyBUF_RECORDS_RO
276
277 This is equivalent to ``(PyBUF_STRIDES | PyBUF_FORMAT)``.
278
279 .. cmacro:: PyBUF_FULL
280
281 This is equivalent to ``(PyBUF_INDIRECT | PyBUF_FORMAT |
282 PyBUF_WRITABLE)``.
283
284 .. cmacro:: PyBUF_FULL_RO
285
286 This is equivalent to ``(PyBUF_INDIRECT | PyBUF_FORMAT)``.
287
288 .. cmacro:: PyBUF_CONTIG
289
290 This is equivalent to ``(PyBUF_ND | PyBUF_WRITABLE)``.
291
292 .. cmacro:: PyBUF_CONTIG_RO
293
294 This is equivalent to ``(PyBUF_ND)``.
Georg Brandl54a3faa2008-01-20 09:30:57 +0000295
296
Brian Curtine040dd52010-06-08 22:30:34 +0000297.. cfunction:: void PyBuffer_Release(Py_buffer *view)
Georg Brandl54a3faa2008-01-20 09:30:57 +0000298
Brian Curtine040dd52010-06-08 22:30:34 +0000299 Release the buffer *view*. This should be called when the buffer is no
300 longer being used as it may free memory from it.
Georg Brandl54a3faa2008-01-20 09:30:57 +0000301
302
Benjamin Peterson9d0ced32008-09-16 02:24:31 +0000303.. cfunction:: Py_ssize_t PyBuffer_SizeFromFormat(const char *)
Georg Brandl54a3faa2008-01-20 09:30:57 +0000304
Benjamin Peterson9d0ced32008-09-16 02:24:31 +0000305 Return the implied :cdata:`~Py_buffer.itemsize` from the struct-stype
306 :cdata:`~Py_buffer.format`.
Georg Brandl54a3faa2008-01-20 09:30:57 +0000307
308
Benjamin Peterson9d0ced32008-09-16 02:24:31 +0000309.. cfunction:: int PyBuffer_IsContiguous(Py_buffer *view, char fortran)
Georg Brandl54a3faa2008-01-20 09:30:57 +0000310
Benjamin Peterson9d0ced32008-09-16 02:24:31 +0000311 Return 1 if the memory defined by the *view* is C-style (*fortran* is
312 ``'C'``) or Fortran-style (*fortran* is ``'F'``) contiguous or either one
313 (*fortran* is ``'A'``). Return 0 otherwise.
314
315
316.. cfunction:: void PyBuffer_FillContiguousStrides(int ndim, Py_ssize_t *shape, Py_ssize_t *strides, Py_ssize_t itemsize, char fortran)
317
318 Fill the *strides* array with byte-strides of a contiguous (C-style if
Ezio Melotti261d8552011-05-20 15:04:38 +0300319 *fortran* is ``'C'`` or Fortran-style if *fortran* is ``'F'``) array of the
Benjamin Peterson9d0ced32008-09-16 02:24:31 +0000320 given shape with the given number of bytes per element.
321
322
Georg Brandl8ffe0bc2010-10-06 07:17:29 +0000323.. cfunction:: int PyBuffer_FillInfo(Py_buffer *view, PyObject *obj, void *buf, Py_ssize_t len, int readonly, int infoflags)
Benjamin Peterson9d0ced32008-09-16 02:24:31 +0000324
325 Fill in a buffer-info structure, *view*, correctly for an exporter that can
326 only share a contiguous chunk of memory of "unsigned bytes" of the given
327 length. Return 0 on success and -1 (with raising an error) on error.
328