blob: 66b4ddd9d008da27af713aed18a7c71b99e00aac [file] [log] [blame]
Georg Brandlf6842722008-01-19 22:08:21 +00001.. highlightlang:: c
2
3.. _bufferobjects:
4
Antoine Pitrou789be0c2009-04-02 21:18:34 +00005Buffers and Memoryview Objects
6------------------------------
Georg Brandlf6842722008-01-19 22:08:21 +00007
8.. sectionauthor:: Greg Stein <gstein@lyra.org>
Antoine Pitrou789be0c2009-04-02 21:18:34 +00009.. sectionauthor:: Benjamin Peterson
Georg Brandlf6842722008-01-19 22:08:21 +000010
11
12.. index::
13 object: buffer
14 single: buffer interface
15
16Python objects implemented in C can export a group of functions called the
Jeroen Ruigrok van der Werven1ae8c882009-04-25 19:04:15 +000017"buffer interface." These functions can be used by an object to expose its
18data in a raw, byte-oriented format. Clients of the object can use the buffer
19interface to access the object data directly, without needing to copy it
20first.
Georg Brandlf6842722008-01-19 22:08:21 +000021
22Two examples of objects that support the buffer interface are strings and
23arrays. The string object exposes the character contents in the buffer
24interface's byte-oriented form. An array can also expose its contents, but it
25should be noted that array elements may be multi-byte values.
26
27An example user of the buffer interface is the file object's :meth:`write`
28method. Any object that can export a series of bytes through the buffer
29interface can be written to a file. There are a number of format codes to
30:cfunc:`PyArg_ParseTuple` that operate against an object's buffer interface,
31returning data from the target object.
32
Antoine Pitrou789be0c2009-04-02 21:18:34 +000033Starting from version 1.6, Python has been providing Python-level buffer
Georg Brandld7d4fd72009-07-26 14:37:28 +000034objects and a C-level buffer API so that any built-in or used-defined type can
Jeroen Ruigrok van der Werven1ae8c882009-04-25 19:04:15 +000035expose its characteristics. Both, however, have been deprecated because of
36various shortcomings, and have been officially removed in Python 3.0 in favour
37of a new C-level buffer API and a new Python-level object named
Antoine Pitrou789be0c2009-04-02 21:18:34 +000038:class:`memoryview`.
39
40The new buffer API has been backported to Python 2.6, and the
41:class:`memoryview` object has been backported to Python 2.7. It is strongly
42advised to use them rather than the old APIs, unless you are blocked from
43doing so for compatibility reasons.
44
45
46The new-style Py_buffer struct
47==============================
48
49
50.. ctype:: Py_buffer
51
52 .. cmember:: void *buf
53
54 A pointer to the start of the memory for the object.
55
56 .. cmember:: Py_ssize_t len
57 :noindex:
58
59 The total length of the memory in bytes.
60
61 .. cmember:: int readonly
62
63 An indicator of whether the buffer is read only.
64
65 .. cmember:: const char *format
66 :noindex:
67
Jeroen Ruigrok van der Werven1ae8c882009-04-25 19:04:15 +000068 A *NULL* terminated string in :mod:`struct` module style syntax giving
69 the contents of the elements available through the buffer. If this is
70 *NULL*, ``"B"`` (unsigned bytes) is assumed.
Antoine Pitrou789be0c2009-04-02 21:18:34 +000071
72 .. cmember:: int ndim
73
74 The number of dimensions the memory represents as a multi-dimensional
75 array. If it is 0, :cdata:`strides` and :cdata:`suboffsets` must be
76 *NULL*.
77
78 .. cmember:: Py_ssize_t *shape
79
80 An array of :ctype:`Py_ssize_t`\s the length of :cdata:`ndim` giving the
81 shape of the memory as a multi-dimensional array. Note that
82 ``((*shape)[0] * ... * (*shape)[ndims-1])*itemsize`` should be equal to
83 :cdata:`len`.
84
85 .. cmember:: Py_ssize_t *strides
86
87 An array of :ctype:`Py_ssize_t`\s the length of :cdata:`ndim` giving the
88 number of bytes to skip to get to a new element in each dimension.
89
90 .. cmember:: Py_ssize_t *suboffsets
91
92 An array of :ctype:`Py_ssize_t`\s the length of :cdata:`ndim`. If these
93 suboffset numbers are greater than or equal to 0, then the value stored
94 along the indicated dimension is a pointer and the suboffset value
95 dictates how many bytes to add to the pointer after de-referencing. A
96 suboffset value that it negative indicates that no de-referencing should
97 occur (striding in a contiguous memory block).
98
99 Here is a function that returns a pointer to the element in an N-D array
100 pointed to by an N-dimesional index when there are both non-NULL strides
101 and suboffsets::
102
103 void *get_item_pointer(int ndim, void *buf, Py_ssize_t *strides,
104 Py_ssize_t *suboffsets, Py_ssize_t *indices) {
105 char *pointer = (char*)buf;
106 int i;
107 for (i = 0; i < ndim; i++) {
108 pointer += strides[i] * indices[i];
109 if (suboffsets[i] >=0 ) {
110 pointer = *((char**)pointer) + suboffsets[i];
111 }
112 }
113 return (void*)pointer;
114 }
115
116
117 .. cmember:: Py_ssize_t itemsize
118
119 This is a storage for the itemsize (in bytes) of each element of the
Jeroen Ruigrok van der Werven1ae8c882009-04-25 19:04:15 +0000120 shared memory. It is technically un-necessary as it can be obtained
121 using :cfunc:`PyBuffer_SizeFromFormat`, however an exporter may know
122 this information without parsing the format string and it is necessary
123 to know the itemsize for proper interpretation of striding. Therefore,
124 storing it is more convenient and faster.
Antoine Pitrou789be0c2009-04-02 21:18:34 +0000125
126 .. cmember:: void *internal
127
128 This is for use internally by the exporting object. For example, this
129 might be re-cast as an integer by the exporter and used to store flags
130 about whether or not the shape, strides, and suboffsets arrays must be
131 freed when the buffer is released. The consumer should never alter this
132 value.
133
134
135Buffer related functions
136========================
137
138
139.. cfunction:: int PyObject_CheckBuffer(PyObject *obj)
140
141 Return 1 if *obj* supports the buffer interface otherwise 0.
142
143
Benjamin Petersond7ead0c2009-05-31 00:42:42 +0000144.. cfunction:: int PyObject_GetBuffer(PyObject *obj, Py_buffer *view, int flags)
Antoine Pitrou789be0c2009-04-02 21:18:34 +0000145
146 Export *obj* into a :ctype:`Py_buffer`, *view*. These arguments must
Jeroen Ruigrok van der Werven1ae8c882009-04-25 19:04:15 +0000147 never be *NULL*. The *flags* argument is a bit field indicating what
148 kind of buffer the caller is prepared to deal with and therefore what
149 kind of buffer the exporter is allowed to return. The buffer interface
150 allows for complicated memory sharing possibilities, but some caller may
Georg Brandl4a46e1c2009-08-06 17:43:55 +0000151 not be able to handle all the complexity but may want to see if the
Jeroen Ruigrok van der Werven1ae8c882009-04-25 19:04:15 +0000152 exporter will let them take a simpler view to its memory.
Antoine Pitrou789be0c2009-04-02 21:18:34 +0000153
154 Some exporters may not be able to share memory in every possible way and
155 may need to raise errors to signal to some consumers that something is
156 just not possible. These errors should be a :exc:`BufferError` unless
Jeroen Ruigrok van der Werven1ae8c882009-04-25 19:04:15 +0000157 there is another error that is actually causing the problem. The
158 exporter can use flags information to simplify how much of the
159 :cdata:`Py_buffer` structure is filled in with non-default values and/or
160 raise an error if the object can't support a simpler view of its memory.
Antoine Pitrou789be0c2009-04-02 21:18:34 +0000161
162 0 is returned on success and -1 on error.
163
164 The following table gives possible values to the *flags* arguments.
165
166 +------------------------------+---------------------------------------------------+
167 | Flag | Description |
168 +==============================+===================================================+
169 | :cmacro:`PyBUF_SIMPLE` | This is the default flag state. The returned |
170 | | buffer may or may not have writable memory. The |
171 | | format of the data will be assumed to be unsigned |
172 | | bytes. This is a "stand-alone" flag constant. It |
173 | | never needs to be '|'d to the others. The exporter|
174 | | will raise an error if it cannot provide such a |
175 | | contiguous buffer of bytes. |
176 | | |
177 +------------------------------+---------------------------------------------------+
178 | :cmacro:`PyBUF_WRITABLE` | The returned buffer must be writable. If it is |
179 | | not writable, then raise an error. |
180 +------------------------------+---------------------------------------------------+
181 | :cmacro:`PyBUF_STRIDES` | This implies :cmacro:`PyBUF_ND`. The returned |
182 | | buffer must provide strides information (i.e. the |
183 | | strides cannot be NULL). This would be used when |
184 | | the consumer can handle strided, discontiguous |
185 | | arrays. Handling strides automatically assumes |
186 | | you can handle shape. The exporter can raise an |
187 | | error if a strided representation of the data is |
188 | | not possible (i.e. without the suboffsets). |
189 | | |
190 +------------------------------+---------------------------------------------------+
191 | :cmacro:`PyBUF_ND` | The returned buffer must provide shape |
192 | | information. The memory will be assumed C-style |
193 | | contiguous (last dimension varies the |
194 | | fastest). The exporter may raise an error if it |
195 | | cannot provide this kind of contiguous buffer. If |
196 | | this is not given then shape will be *NULL*. |
197 | | |
198 | | |
199 | | |
200 +------------------------------+---------------------------------------------------+
201 |:cmacro:`PyBUF_C_CONTIGUOUS` | These flags indicate that the contiguity returned |
202 |:cmacro:`PyBUF_F_CONTIGUOUS` | buffer must be respectively, C-contiguous (last |
203 |:cmacro:`PyBUF_ANY_CONTIGUOUS`| dimension varies the fastest), Fortran contiguous |
204 | | (first dimension varies the fastest) or either |
205 | | one. All of these flags imply |
206 | | :cmacro:`PyBUF_STRIDES` and guarantee that the |
207 | | strides buffer info structure will be filled in |
208 | | correctly. |
209 | | |
210 +------------------------------+---------------------------------------------------+
211 | :cmacro:`PyBUF_INDIRECT` | This flag indicates the returned buffer must have |
212 | | suboffsets information (which can be NULL if no |
213 | | suboffsets are needed). This can be used when |
214 | | the consumer can handle indirect array |
215 | | referencing implied by these suboffsets. This |
216 | | implies :cmacro:`PyBUF_STRIDES`. |
217 | | |
218 | | |
219 | | |
220 +------------------------------+---------------------------------------------------+
221 | :cmacro:`PyBUF_FORMAT` | The returned buffer must have true format |
222 | | information if this flag is provided. This would |
223 | | be used when the consumer is going to be checking |
224 | | for what 'kind' of data is actually stored. An |
225 | | exporter should always be able to provide this |
226 | | information if requested. If format is not |
227 | | explicitly requested then the format must be |
228 | | returned as *NULL* (which means ``'B'``, or |
229 | | unsigned bytes) |
230 +------------------------------+---------------------------------------------------+
231 | :cmacro:`PyBUF_STRIDED` | This is equivalent to ``(PyBUF_STRIDES | |
232 | | PyBUF_WRITABLE)``. |
233 +------------------------------+---------------------------------------------------+
234 | :cmacro:`PyBUF_STRIDED_RO` | This is equivalent to ``(PyBUF_STRIDES)``. |
235 | | |
236 +------------------------------+---------------------------------------------------+
237 | :cmacro:`PyBUF_RECORDS` | This is equivalent to ``(PyBUF_STRIDES | |
238 | | PyBUF_FORMAT | PyBUF_WRITABLE)``. |
239 +------------------------------+---------------------------------------------------+
240 | :cmacro:`PyBUF_RECORDS_RO` | This is equivalent to ``(PyBUF_STRIDES | |
241 | | PyBUF_FORMAT)``. |
242 +------------------------------+---------------------------------------------------+
243 | :cmacro:`PyBUF_FULL` | This is equivalent to ``(PyBUF_INDIRECT | |
244 | | PyBUF_FORMAT | PyBUF_WRITABLE)``. |
245 +------------------------------+---------------------------------------------------+
Georg Brandl6cb1ff32009-04-08 16:36:39 +0000246 | :cmacro:`PyBUF_FULL_RO` | This is equivalent to ``(PyBUF_INDIRECT | |
Antoine Pitrou789be0c2009-04-02 21:18:34 +0000247 | | PyBUF_FORMAT)``. |
248 +------------------------------+---------------------------------------------------+
249 | :cmacro:`PyBUF_CONTIG` | This is equivalent to ``(PyBUF_ND | |
250 | | PyBUF_WRITABLE)``. |
251 +------------------------------+---------------------------------------------------+
252 | :cmacro:`PyBUF_CONTIG_RO` | This is equivalent to ``(PyBUF_ND)``. |
253 | | |
254 +------------------------------+---------------------------------------------------+
255
256
Georg Brandleb4781c2009-09-02 20:37:16 +0000257.. cfunction:: void PyBuffer_Release(Py_buffer *view)
Antoine Pitrou789be0c2009-04-02 21:18:34 +0000258
Georg Brandleb4781c2009-09-02 20:37:16 +0000259 Release the buffer *view*. This should be called when the buffer
Antoine Pitrou789be0c2009-04-02 21:18:34 +0000260 is no longer being used as it may free memory from it.
261
262
263.. cfunction:: Py_ssize_t PyBuffer_SizeFromFormat(const char *)
264
265 Return the implied :cdata:`~Py_buffer.itemsize` from the struct-stype
266 :cdata:`~Py_buffer.format`.
267
268
269.. cfunction:: int PyObject_CopyToObject(PyObject *obj, void *buf, Py_ssize_t len, char fortran)
270
Jeroen Ruigrok van der Werven1ae8c882009-04-25 19:04:15 +0000271 Copy *len* bytes of data pointed to by the contiguous chunk of memory
272 pointed to by *buf* into the buffer exported by obj. The buffer must of
273 course be writable. Return 0 on success and return -1 and raise an error
274 on failure. If the object does not have a writable buffer, then an error
275 is raised. If *fortran* is ``'F'``, then if the object is
276 multi-dimensional, then the data will be copied into the array in
277 Fortran-style (first dimension varies the fastest). If *fortran* is
278 ``'C'``, then the data will be copied into the array in C-style (last
279 dimension varies the fastest). If *fortran* is ``'A'``, then it does not
280 matter and the copy will be made in whatever way is more efficient.
Antoine Pitrou789be0c2009-04-02 21:18:34 +0000281
282
283.. cfunction:: int PyBuffer_IsContiguous(Py_buffer *view, char fortran)
284
285 Return 1 if the memory defined by the *view* is C-style (*fortran* is
286 ``'C'``) or Fortran-style (*fortran* is ``'F'``) contiguous or either one
287 (*fortran* is ``'A'``). Return 0 otherwise.
288
289
290.. cfunction:: void PyBuffer_FillContiguousStrides(int ndim, Py_ssize_t *shape, Py_ssize_t *strides, Py_ssize_t itemsize, char fortran)
291
292 Fill the *strides* array with byte-strides of a contiguous (C-style if
293 *fortran* is ``'C'`` or Fortran-style if *fortran* is ``'F'`` array of the
294 given shape with the given number of bytes per element.
295
296
Georg Brandl1686f342009-12-28 07:59:05 +0000297.. cfunction:: int PyBuffer_FillInfo(Py_buffer *view, PyObject *obj, void *buf, Py_ssize_t len, int readonly, int infoflags)
Antoine Pitrou789be0c2009-04-02 21:18:34 +0000298
299 Fill in a buffer-info structure, *view*, correctly for an exporter that can
300 only share a contiguous chunk of memory of "unsigned bytes" of the given
301 length. Return 0 on success and -1 (with raising an error) on error.
302
303
304MemoryView objects
305==================
306
307A memoryview object is an extended buffer object that could replace the buffer
308object (but doesn't have to as that could be kept as a simple 1-d memoryview
309object). It, unlike :ctype:`Py_buffer`, is a Python object (exposed as
310:class:`memoryview` in :mod:`builtins`), so it can be used with Python code.
311
312.. cfunction:: PyObject* PyMemoryView_FromObject(PyObject *obj)
313
314 Return a memoryview object from an object that defines the buffer interface.
315
316
317Old-style buffer objects
318========================
319
Georg Brandlf6842722008-01-19 22:08:21 +0000320.. index:: single: PyBufferProcs
321
Antoine Pitrou789be0c2009-04-02 21:18:34 +0000322More information on the old buffer interface is provided in the section
Georg Brandlf6842722008-01-19 22:08:21 +0000323:ref:`buffer-structs`, under the description for :ctype:`PyBufferProcs`.
324
325A "buffer object" is defined in the :file:`bufferobject.h` header (included by
326:file:`Python.h`). These objects look very similar to string objects at the
327Python programming level: they support slicing, indexing, concatenation, and
Jeroen Ruigrok van der Werven1ae8c882009-04-25 19:04:15 +0000328some other standard string operations. However, their data can come from one
329of two sources: from a block of memory, or from another object which exports
330the buffer interface.
Georg Brandlf6842722008-01-19 22:08:21 +0000331
332Buffer objects are useful as a way to expose the data from another object's
Jeroen Ruigrok van der Werven1ae8c882009-04-25 19:04:15 +0000333buffer interface to the Python programmer. They can also be used as a
334zero-copy slicing mechanism. Using their ability to reference a block of
335memory, it is possible to expose any data to the Python programmer quite
336easily. The memory could be a large, constant array in a C extension, it could
337be a raw block of memory for manipulation before passing to an operating
338system library, or it could be used to pass around structured data in its
339native, in-memory format.
Georg Brandlf6842722008-01-19 22:08:21 +0000340
341
342.. ctype:: PyBufferObject
343
344 This subtype of :ctype:`PyObject` represents a buffer object.
345
346
347.. cvar:: PyTypeObject PyBuffer_Type
348
349 .. index:: single: BufferType (in module types)
350
351 The instance of :ctype:`PyTypeObject` which represents the Python buffer type;
352 it is the same object as ``buffer`` and ``types.BufferType`` in the Python
353 layer. .
354
355
356.. cvar:: int Py_END_OF_BUFFER
357
358 This constant may be passed as the *size* parameter to
359 :cfunc:`PyBuffer_FromObject` or :cfunc:`PyBuffer_FromReadWriteObject`. It
Jeroen Ruigrok van der Werven1ae8c882009-04-25 19:04:15 +0000360 indicates that the new :ctype:`PyBufferObject` should refer to *base*
361 object from the specified *offset* to the end of its exported buffer.
362 Using this enables the caller to avoid querying the *base* object for its
363 length.
Georg Brandlf6842722008-01-19 22:08:21 +0000364
365
366.. cfunction:: int PyBuffer_Check(PyObject *p)
367
368 Return true if the argument has type :cdata:`PyBuffer_Type`.
369
370
371.. cfunction:: PyObject* PyBuffer_FromObject(PyObject *base, Py_ssize_t offset, Py_ssize_t size)
372
Jeroen Ruigrok van der Werven1ae8c882009-04-25 19:04:15 +0000373 Return a new read-only buffer object. This raises :exc:`TypeError` if
374 *base* doesn't support the read-only buffer protocol or doesn't provide
375 exactly one buffer segment, or it raises :exc:`ValueError` if *offset* is
376 less than zero. The buffer will hold a reference to the *base* object, and
377 the buffer's contents will refer to the *base* object's buffer interface,
378 starting as position *offset* and extending for *size* bytes. If *size* is
379 :const:`Py_END_OF_BUFFER`, then the new buffer's contents extend to the
380 length of the *base* object's exported buffer data.
Georg Brandlf6842722008-01-19 22:08:21 +0000381
Jeroen Ruigrok van der Werven089c5cd2009-04-25 17:59:03 +0000382 .. versionchanged:: 2.5
383 This function used an :ctype:`int` type for *offset* and *size*. This
384 might require changes in your code for properly supporting 64-bit
385 systems.
386
Georg Brandlf6842722008-01-19 22:08:21 +0000387
388.. cfunction:: PyObject* PyBuffer_FromReadWriteObject(PyObject *base, Py_ssize_t offset, Py_ssize_t size)
389
Jeroen Ruigrok van der Werven1ae8c882009-04-25 19:04:15 +0000390 Return a new writable buffer object. Parameters and exceptions are similar
391 to those for :cfunc:`PyBuffer_FromObject`. If the *base* object does not
392 export the writeable buffer protocol, then :exc:`TypeError` is raised.
Georg Brandlf6842722008-01-19 22:08:21 +0000393
Jeroen Ruigrok van der Werven089c5cd2009-04-25 17:59:03 +0000394 .. versionchanged:: 2.5
395 This function used an :ctype:`int` type for *offset* and *size*. This
396 might require changes in your code for properly supporting 64-bit
397 systems.
398
Georg Brandlf6842722008-01-19 22:08:21 +0000399
400.. cfunction:: PyObject* PyBuffer_FromMemory(void *ptr, Py_ssize_t size)
401
Jeroen Ruigrok van der Werven1ae8c882009-04-25 19:04:15 +0000402 Return a new read-only buffer object that reads from a specified location
403 in memory, with a specified size. The caller is responsible for ensuring
404 that the memory buffer, passed in as *ptr*, is not deallocated while the
405 returned buffer object exists. Raises :exc:`ValueError` if *size* is less
406 than zero. Note that :const:`Py_END_OF_BUFFER` may *not* be passed for the
407 *size* parameter; :exc:`ValueError` will be raised in that case.
Georg Brandlf6842722008-01-19 22:08:21 +0000408
Jeroen Ruigrok van der Werven089c5cd2009-04-25 17:59:03 +0000409 .. versionchanged:: 2.5
410 This function used an :ctype:`int` type for *size*. This might require
411 changes in your code for properly supporting 64-bit systems.
412
Georg Brandlf6842722008-01-19 22:08:21 +0000413
414.. cfunction:: PyObject* PyBuffer_FromReadWriteMemory(void *ptr, Py_ssize_t size)
415
Jeroen Ruigrok van der Werven1ae8c882009-04-25 19:04:15 +0000416 Similar to :cfunc:`PyBuffer_FromMemory`, but the returned buffer is
417 writable.
Georg Brandlf6842722008-01-19 22:08:21 +0000418
Jeroen Ruigrok van der Werven089c5cd2009-04-25 17:59:03 +0000419 .. versionchanged:: 2.5
420 This function used an :ctype:`int` type for *size*. This might require
421 changes in your code for properly supporting 64-bit systems.
422
Georg Brandlf6842722008-01-19 22:08:21 +0000423
424.. cfunction:: PyObject* PyBuffer_New(Py_ssize_t size)
425
426 Return a new writable buffer object that maintains its own memory buffer of
Jeroen Ruigrok van der Werven1ae8c882009-04-25 19:04:15 +0000427 *size* bytes. :exc:`ValueError` is returned if *size* is not zero or
428 positive. Note that the memory buffer (as returned by
429 :cfunc:`PyObject_AsWriteBuffer`) is not specifically aligned.
Jeroen Ruigrok van der Werven089c5cd2009-04-25 17:59:03 +0000430
431 .. versionchanged:: 2.5
432 This function used an :ctype:`int` type for *size*. This might require
433 changes in your code for properly supporting 64-bit systems.