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