source: python/trunk/Doc/c-api/buffer.rst

Last change on this file was 391, checked in by dmik, 11 years ago

python: Merge vendor 2.7.6 to trunk.

  • Property svn:eol-style set to native
File size: 22.2 KB
RevLine 
[2]1.. highlightlang:: c
2
3.. _bufferobjects:
4
[391]5Buffers and Memoryview Objects
6------------------------------
[2]7
8.. sectionauthor:: Greg Stein <gstein@lyra.org>
[391]9.. sectionauthor:: Benjamin Peterson
[2]10
11
12.. index::
13 object: buffer
14 single: buffer interface
15
16Python objects implemented in C can export a group of functions called the
17"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.
21
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
[391]30:c:func:`PyArg_ParseTuple` that operate against an object's buffer interface,
[2]31returning data from the target object.
32
33Starting from version 1.6, Python has been providing Python-level buffer
34objects and a C-level buffer API so that any built-in or used-defined type can
35expose its characteristics. Both, however, have been deprecated because of
[391]36various shortcomings, and have been officially removed in Python 3 in favour
[2]37of a new C-level buffer API and a new Python-level object named
38: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
[391]50.. c:type:: Py_buffer
[2]51
[391]52 .. c:member:: void *buf
[2]53
54 A pointer to the start of the memory for the object.
55
[391]56 .. c:member:: Py_ssize_t len
[2]57 :noindex:
58
59 The total length of the memory in bytes.
60
[391]61 .. c:member:: int readonly
[2]62
63 An indicator of whether the buffer is read only.
64
[391]65 .. c:member:: const char *format
[2]66 :noindex:
67
68 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.
71
[391]72 .. c:member:: int ndim
[2]73
74 The number of dimensions the memory represents as a multi-dimensional
[391]75 array. If it is 0, :c:data:`strides` and :c:data:`suboffsets` must be
[2]76 *NULL*.
77
[391]78 .. c:member:: Py_ssize_t *shape
[2]79
[391]80 An array of :c:type:`Py_ssize_t`\s the length of :c:data:`ndim` giving the
[2]81 shape of the memory as a multi-dimensional array. Note that
82 ``((*shape)[0] * ... * (*shape)[ndims-1])*itemsize`` should be equal to
[391]83 :c:data:`len`.
[2]84
[391]85 .. c:member:: Py_ssize_t *strides
[2]86
[391]87 An array of :c:type:`Py_ssize_t`\s the length of :c:data:`ndim` giving the
[2]88 number of bytes to skip to get to a new element in each dimension.
89
[391]90 .. c:member:: Py_ssize_t *suboffsets
[2]91
[391]92 An array of :c:type:`Py_ssize_t`\s the length of :c:data:`ndim`. If these
[2]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
[391]117 .. c:member:: Py_ssize_t itemsize
[2]118
119 This is a storage for the itemsize (in bytes) of each element of the
120 shared memory. It is technically un-necessary as it can be obtained
[391]121 using :c:func:`PyBuffer_SizeFromFormat`, however an exporter may know
[2]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.
125
[391]126 .. c:member:: void *internal
[2]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
[391]139.. c:function:: int PyObject_CheckBuffer(PyObject *obj)
[2]140
141 Return 1 if *obj* supports the buffer interface otherwise 0.
142
143
[391]144.. c:function:: int PyObject_GetBuffer(PyObject *obj, Py_buffer *view, int flags)
[2]145
[391]146 Export *obj* into a :c:type:`Py_buffer`, *view*. These arguments must
[2]147 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
151 not be able to handle all the complexity but may want to see if the
152 exporter will let them take a simpler view to its memory.
153
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
157 there is another error that is actually causing the problem. The
158 exporter can use flags information to simplify how much of the
[391]159 :c:data:`Py_buffer` structure is filled in with non-default values and/or
[2]160 raise an error if the object can't support a simpler view of its memory.
161
162 0 is returned on success and -1 on error.
163
164 The following table gives possible values to the *flags* arguments.
165
[391]166 +-------------------------------+---------------------------------------------------+
167 | Flag | Description |
168 +===============================+===================================================+
169 | :c:macro:`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 | :c:macro:`PyBUF_WRITABLE` | The returned buffer must be writable. If it is |
179 | | not writable, then raise an error. |
180 +-------------------------------+---------------------------------------------------+
181 | :c:macro:`PyBUF_STRIDES` | This implies :c:macro:`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 | :c:macro:`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 |:c:macro:`PyBUF_C_CONTIGUOUS` | These flags indicate that the contiguity returned |
202 |:c:macro:`PyBUF_F_CONTIGUOUS` | buffer must be respectively, C-contiguous (last |
203 |:c:macro:`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 | | :c:macro:`PyBUF_STRIDES` and guarantee that the |
207 | | strides buffer info structure will be filled in |
208 | | correctly. |
209 | | |
210 +-------------------------------+---------------------------------------------------+
211 | :c:macro:`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 :c:macro:`PyBUF_STRIDES`. |
217 | | |
218 | | |
219 | | |
220 +-------------------------------+---------------------------------------------------+
221 | :c:macro:`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 | :c:macro:`PyBUF_STRIDED` | This is equivalent to ``(PyBUF_STRIDES | |
232 | | PyBUF_WRITABLE)``. |
233 +-------------------------------+---------------------------------------------------+
234 | :c:macro:`PyBUF_STRIDED_RO` | This is equivalent to ``(PyBUF_STRIDES)``. |
235 | | |
236 +-------------------------------+---------------------------------------------------+
237 | :c:macro:`PyBUF_RECORDS` | This is equivalent to ``(PyBUF_STRIDES | |
238 | | PyBUF_FORMAT | PyBUF_WRITABLE)``. |
239 +-------------------------------+---------------------------------------------------+
240 | :c:macro:`PyBUF_RECORDS_RO` | This is equivalent to ``(PyBUF_STRIDES | |
241 | | PyBUF_FORMAT)``. |
242 +-------------------------------+---------------------------------------------------+
243 | :c:macro:`PyBUF_FULL` | This is equivalent to ``(PyBUF_INDIRECT | |
244 | | PyBUF_FORMAT | PyBUF_WRITABLE)``. |
245 +-------------------------------+---------------------------------------------------+
246 | :c:macro:`PyBUF_FULL_RO` | This is equivalent to ``(PyBUF_INDIRECT | |
247 | | PyBUF_FORMAT)``. |
248 +-------------------------------+---------------------------------------------------+
249 | :c:macro:`PyBUF_CONTIG` | This is equivalent to ``(PyBUF_ND | |
250 | | PyBUF_WRITABLE)``. |
251 +-------------------------------+---------------------------------------------------+
252 | :c:macro:`PyBUF_CONTIG_RO` | This is equivalent to ``(PyBUF_ND)``. |
253 | | |
254 +-------------------------------+---------------------------------------------------+
[2]255
256
[391]257.. c:function:: void PyBuffer_Release(Py_buffer *view)
[2]258
259 Release the buffer *view*. This should be called when the buffer
260 is no longer being used as it may free memory from it.
261
262
[391]263.. c:function:: Py_ssize_t PyBuffer_SizeFromFormat(const char *)
[2]264
[391]265 Return the implied :c:data:`~Py_buffer.itemsize` from the struct-stype
266 :c:data:`~Py_buffer.format`.
[2]267
268
[391]269.. c:function:: int PyBuffer_IsContiguous(Py_buffer *view, char fortran)
[2]270
271 Return 1 if the memory defined by the *view* is C-style (*fortran* is
272 ``'C'``) or Fortran-style (*fortran* is ``'F'``) contiguous or either one
273 (*fortran* is ``'A'``). Return 0 otherwise.
274
275
[391]276.. c:function:: void PyBuffer_FillContiguousStrides(int ndim, Py_ssize_t *shape, Py_ssize_t *strides, Py_ssize_t itemsize, char fortran)
[2]277
278 Fill the *strides* array with byte-strides of a contiguous (C-style if
[391]279 *fortran* is ``'C'`` or Fortran-style if *fortran* is ``'F'``) array of the
[2]280 given shape with the given number of bytes per element.
281
282
[391]283.. c:function:: int PyBuffer_FillInfo(Py_buffer *view, PyObject *obj, void *buf, Py_ssize_t len, int readonly, int infoflags)
[2]284
285 Fill in a buffer-info structure, *view*, correctly for an exporter that can
286 only share a contiguous chunk of memory of "unsigned bytes" of the given
287 length. Return 0 on success and -1 (with raising an error) on error.
288
289
[391]290MemoryView objects
291==================
292
293.. versionadded:: 2.7
294
295A :class:`memoryview` object exposes the new C level buffer interface as a
296Python object which can then be passed around like any other object.
297
298.. c:function:: PyObject *PyMemoryView_FromObject(PyObject *obj)
299
300 Create a memoryview object from an object that defines the new buffer
301 interface.
302
303
304.. c:function:: PyObject *PyMemoryView_FromBuffer(Py_buffer *view)
305
306 Create a memoryview object wrapping the given buffer-info structure *view*.
307 The memoryview object then owns the buffer, which means you shouldn't
308 try to release it yourself: it will be released on deallocation of the
309 memoryview object.
310
311
312.. c:function:: PyObject *PyMemoryView_GetContiguous(PyObject *obj, int buffertype, char order)
313
314 Create a memoryview object to a contiguous chunk of memory (in either
315 'C' or 'F'ortran *order*) from an object that defines the buffer
316 interface. If memory is contiguous, the memoryview object points to the
317 original memory. Otherwise copy is made and the memoryview points to a
318 new bytes object.
319
320
321.. c:function:: int PyMemoryView_Check(PyObject *obj)
322
323 Return true if the object *obj* is a memoryview object. It is not
324 currently allowed to create subclasses of :class:`memoryview`.
325
326
327.. c:function:: Py_buffer *PyMemoryView_GET_BUFFER(PyObject *obj)
328
329 Return a pointer to the buffer-info structure wrapped by the given
330 object. The object **must** be a memoryview instance; this macro doesn't
331 check its type, you must do it yourself or you will risk crashes.
332
333
[2]334Old-style buffer objects
335========================
336
337.. index:: single: PyBufferProcs
338
[391]339More information on the old buffer interface is provided in the section
340:ref:`buffer-structs`, under the description for :c:type:`PyBufferProcs`.
[2]341
342A "buffer object" is defined in the :file:`bufferobject.h` header (included by
343:file:`Python.h`). These objects look very similar to string objects at the
344Python programming level: they support slicing, indexing, concatenation, and
345some other standard string operations. However, their data can come from one
346of two sources: from a block of memory, or from another object which exports
347the buffer interface.
348
349Buffer objects are useful as a way to expose the data from another object's
350buffer interface to the Python programmer. They can also be used as a
351zero-copy slicing mechanism. Using their ability to reference a block of
352memory, it is possible to expose any data to the Python programmer quite
353easily. The memory could be a large, constant array in a C extension, it could
354be a raw block of memory for manipulation before passing to an operating
355system library, or it could be used to pass around structured data in its
356native, in-memory format.
357
358
[391]359.. c:type:: PyBufferObject
[2]360
[391]361 This subtype of :c:type:`PyObject` represents a buffer object.
[2]362
363
[391]364.. c:var:: PyTypeObject PyBuffer_Type
[2]365
366 .. index:: single: BufferType (in module types)
367
[391]368 The instance of :c:type:`PyTypeObject` which represents the Python buffer type;
[2]369 it is the same object as ``buffer`` and ``types.BufferType`` in the Python
370 layer. .
371
372
[391]373.. c:var:: int Py_END_OF_BUFFER
[2]374
375 This constant may be passed as the *size* parameter to
[391]376 :c:func:`PyBuffer_FromObject` or :c:func:`PyBuffer_FromReadWriteObject`. It
377 indicates that the new :c:type:`PyBufferObject` should refer to *base*
[2]378 object from the specified *offset* to the end of its exported buffer.
379 Using this enables the caller to avoid querying the *base* object for its
380 length.
381
382
[391]383.. c:function:: int PyBuffer_Check(PyObject *p)
[2]384
[391]385 Return true if the argument has type :c:data:`PyBuffer_Type`.
[2]386
387
[391]388.. c:function:: PyObject* PyBuffer_FromObject(PyObject *base, Py_ssize_t offset, Py_ssize_t size)
[2]389
390 Return a new read-only buffer object. This raises :exc:`TypeError` if
391 *base* doesn't support the read-only buffer protocol or doesn't provide
392 exactly one buffer segment, or it raises :exc:`ValueError` if *offset* is
393 less than zero. The buffer will hold a reference to the *base* object, and
394 the buffer's contents will refer to the *base* object's buffer interface,
395 starting as position *offset* and extending for *size* bytes. If *size* is
396 :const:`Py_END_OF_BUFFER`, then the new buffer's contents extend to the
397 length of the *base* object's exported buffer data.
398
399 .. versionchanged:: 2.5
[391]400 This function used an :c:type:`int` type for *offset* and *size*. This
[2]401 might require changes in your code for properly supporting 64-bit
402 systems.
403
404
[391]405.. c:function:: PyObject* PyBuffer_FromReadWriteObject(PyObject *base, Py_ssize_t offset, Py_ssize_t size)
[2]406
407 Return a new writable buffer object. Parameters and exceptions are similar
[391]408 to those for :c:func:`PyBuffer_FromObject`. If the *base* object does not
[2]409 export the writeable buffer protocol, then :exc:`TypeError` is raised.
410
411 .. versionchanged:: 2.5
[391]412 This function used an :c:type:`int` type for *offset* and *size*. This
[2]413 might require changes in your code for properly supporting 64-bit
414 systems.
415
416
[391]417.. c:function:: PyObject* PyBuffer_FromMemory(void *ptr, Py_ssize_t size)
[2]418
419 Return a new read-only buffer object that reads from a specified location
420 in memory, with a specified size. The caller is responsible for ensuring
421 that the memory buffer, passed in as *ptr*, is not deallocated while the
422 returned buffer object exists. Raises :exc:`ValueError` if *size* is less
423 than zero. Note that :const:`Py_END_OF_BUFFER` may *not* be passed for the
424 *size* parameter; :exc:`ValueError` will be raised in that case.
425
426 .. versionchanged:: 2.5
[391]427 This function used an :c:type:`int` type for *size*. This might require
[2]428 changes in your code for properly supporting 64-bit systems.
429
430
[391]431.. c:function:: PyObject* PyBuffer_FromReadWriteMemory(void *ptr, Py_ssize_t size)
[2]432
[391]433 Similar to :c:func:`PyBuffer_FromMemory`, but the returned buffer is
[2]434 writable.
435
436 .. versionchanged:: 2.5
[391]437 This function used an :c:type:`int` type for *size*. This might require
[2]438 changes in your code for properly supporting 64-bit systems.
439
440
[391]441.. c:function:: PyObject* PyBuffer_New(Py_ssize_t size)
[2]442
443 Return a new writable buffer object that maintains its own memory buffer of
444 *size* bytes. :exc:`ValueError` is returned if *size* is not zero or
445 positive. Note that the memory buffer (as returned by
[391]446 :c:func:`PyObject_AsWriteBuffer`) is not specifically aligned.
[2]447
448 .. versionchanged:: 2.5
[391]449 This function used an :c:type:`int` type for *size*. This might require
[2]450 changes in your code for properly supporting 64-bit systems.
Note: See TracBrowser for help on using the repository browser.