blob: c46028b72a8b66e8656b79b2fc8c2c5b5ba9a321 [file] [log] [blame]
Georg Brandl54a3faa2008-01-20 09:30:57 +00001.. highlightlang:: c
2
3.. _bufferobjects:
4
5Buffer Objects
6--------------
7
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::
13 object: buffer
14 single: buffer interface
15
Benjamin Peterson9d0ced32008-09-16 02:24:31 +000016Python objects implemented in C can export a "buffer interface." These
17functions can be used by an object to expose its data in a raw, byte-oriented
18format. Clients of the object can use the buffer interface to access the object
19data directly, without needing to copy it first.
Georg Brandl54a3faa2008-01-20 09:30:57 +000020
Benjamin Peterson9d0ced32008-09-16 02:24:31 +000021Two examples of objects that support the buffer interface are bytes and
22arrays. The bytes object exposes the character contents in the buffer
Georg Brandl54a3faa2008-01-20 09:30:57 +000023interface'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
32.. index:: single: PyBufferProcs
33
Georg Brandl48310cd2009-01-03 21:18:54 +000034More information on the buffer interface is provided in the section
Georg Brandl54a3faa2008-01-20 09:30:57 +000035:ref:`buffer-structs`, under the description for :ctype:`PyBufferProcs`.
36
Georg Brandl54a3faa2008-01-20 09:30:57 +000037Buffer objects are useful as a way to expose the data from another object's
Benjamin Peterson9d0ced32008-09-16 02:24:31 +000038buffer interface to the Python programmer. They can also be used as a zero-copy
39slicing mechanism. Using their ability to reference a block of memory, it is
40possible to expose any data to the Python programmer quite easily. The memory
Georg Brandl54a3faa2008-01-20 09:30:57 +000041could be a large, constant array in a C extension, it could be a raw block of
42memory for manipulation before passing to an operating system library, or it
43could be used to pass around structured data in its native, in-memory format.
44
45
Benjamin Peterson9d0ced32008-09-16 02:24:31 +000046.. ctype:: Py_buffer
Georg Brandl54a3faa2008-01-20 09:30:57 +000047
Benjamin Peterson9d0ced32008-09-16 02:24:31 +000048 .. cmember:: void *buf
49
50 A pointer to the start of the memory for the object.
51
52 .. cmember:: Py_ssize_t len
Benjamin Petersonf2fa87b2008-09-17 22:59:21 +000053 :noindex:
Benjamin Peterson9d0ced32008-09-16 02:24:31 +000054
55 The total length of the memory in bytes.
56
57 .. cmember:: int readonly
58
59 An indicator of whether the buffer is read only.
60
61 .. cmember:: const char *format
Benjamin Petersonf2fa87b2008-09-17 22:59:21 +000062 :noindex:
Benjamin Peterson9d0ced32008-09-16 02:24:31 +000063
64 A *NULL* terminated string in :mod:`struct` module style syntax giving the
65 contents of the elements available through the buffer. If this is *NULL*,
66 ``"B"`` (unsigned bytes) is assumed.
67
68 .. cmember:: int ndim
69
70 The number of dimensions the memory represents as a multi-dimensional
71 array. If it is 0, :cdata:`strides` and :cdata:`suboffsets` must be
72 *NULL*.
73
74 .. cmember:: Py_ssize_t *shape
75
76 An array of :ctype:`Py_ssize_t`\s the length of :cdata:`ndim` giving the
77 shape of the memory as a multi-dimensional array. Note that
78 ``((*shape)[0] * ... * (*shape)[ndims-1])*itemsize`` should be equal to
79 :cdata:`len`.
80
81 .. cmember:: Py_ssize_t *strides
82
83 An array of :ctype:`Py_ssize_t`\s the length of :cdata:`ndim` giving the
84 number of bytes to skip to get to a new element in each dimension.
85
86 .. cmember:: Py_ssize_t *suboffsets
87
88 An array of :ctype:`Py_ssize_t`\s the length of :cdata:`ndim`. If these
89 suboffset numbers are greater than or equal to 0, then the value stored
90 along the indicated dimension is a pointer and the suboffset value
91 dictates how many bytes to add to the pointer after de-referencing. A
92 suboffset value that it negative indicates that no de-referencing should
93 occur (striding in a contiguous memory block).
94
95 Here is a function that returns a pointer to the element in an N-D array
Georg Brandlae2dbe22009-03-13 19:04:40 +000096 pointed to by an N-dimensional index when there are both non-NULL strides
Benjamin Peterson9d0ced32008-09-16 02:24:31 +000097 and suboffsets::
98
99 void *get_item_pointer(int ndim, void *buf, Py_ssize_t *strides,
100 Py_ssize_t *suboffsets, Py_ssize_t *indices) {
101 char *pointer = (char*)buf;
102 int i;
103 for (i = 0; i < ndim; i++) {
104 pointer += strides[i] * indices[i];
105 if (suboffsets[i] >=0 ) {
106 pointer = *((char**)pointer) + suboffsets[i];
Georg Brandl48310cd2009-01-03 21:18:54 +0000107 }
Benjamin Peterson9d0ced32008-09-16 02:24:31 +0000108 }
109 return (void*)pointer;
110 }
Georg Brandl54a3faa2008-01-20 09:30:57 +0000111
112
Benjamin Peterson9d0ced32008-09-16 02:24:31 +0000113 .. cmember:: Py_ssize_t itemsize
Georg Brandl54a3faa2008-01-20 09:30:57 +0000114
Benjamin Peterson9d0ced32008-09-16 02:24:31 +0000115 This is a storage for the itemsize (in bytes) of each element of the
116 shared memory. It is technically un-necessary as it can be obtained using
117 :cfunc:`PyBuffer_SizeFromFormat`, however an exporter may know this
118 information without parsing the format string and it is necessary to know
119 the itemsize for proper interpretation of striding. Therefore, storing it
120 is more convenient and faster.
Georg Brandl54a3faa2008-01-20 09:30:57 +0000121
Benjamin Peterson9d0ced32008-09-16 02:24:31 +0000122 .. cmember:: void *internal
123
124 This is for use internally by the exporting object. For example, this
125 might be re-cast as an integer by the exporter and used to store flags
126 about whether or not the shape, strides, and suboffsets arrays must be
127 freed when the buffer is released. The consumer should never alter this
128 value.
Georg Brandl54a3faa2008-01-20 09:30:57 +0000129
130
Benjamin Peterson9d0ced32008-09-16 02:24:31 +0000131Buffer related functions
132========================
Georg Brandl54a3faa2008-01-20 09:30:57 +0000133
134
Benjamin Peterson9d0ced32008-09-16 02:24:31 +0000135.. cfunction:: int PyObject_CheckBuffer(PyObject *obj)
Georg Brandl54a3faa2008-01-20 09:30:57 +0000136
Benjamin Peterson9d0ced32008-09-16 02:24:31 +0000137 Return 1 if *obj* supports the buffer interface otherwise 0.
Georg Brandl54a3faa2008-01-20 09:30:57 +0000138
139
Benjamin Peterson9d0ced32008-09-16 02:24:31 +0000140.. cfunction:: int PyObject_GetBuffer(PyObject *obj, PyObject *view, int flags)
Georg Brandl54a3faa2008-01-20 09:30:57 +0000141
Benjamin Peterson9d0ced32008-09-16 02:24:31 +0000142 Export *obj* into a :ctype:`Py_buffer`, *view*. These arguments must
143 never be *NULL*. The *flags* argument is a bit field indicating what kind
144 of buffer the caller is prepared to deal with and therefore what kind of
145 buffer the exporter is allowed to return. The buffer interface allows for
146 complicated memory sharing possibilities, but some caller may not be able
147 to handle all the complexibity but may want to see if the exporter will
148 let them take a simpler view to its memory.
149
150 Some exporters may not be able to share memory in every possible way and
151 may need to raise errors to signal to some consumers that something is
152 just not possible. These errors should be a :exc:`BufferError` unless
153 there is another error that is actually causing the problem. The exporter
154 can use flags information to simplify how much of the :cdata:`Py_buffer`
155 structure is filled in with non-default values and/or raise an error if
156 the object can't support a simpler view of its memory.
157
158 0 is returned on success and -1 on error.
159
160 The following table gives possible values to the *flags* arguments.
161
Benjamin Petersonc1f44af2008-11-20 22:38:20 +0000162 +------------------------------+---------------------------------------------------+
163 | Flag | Description |
164 +==============================+===================================================+
165 | :cmacro:`PyBUF_SIMPLE` | This is the default flag state. The returned |
166 | | buffer may or may not have writable memory. The |
167 | | format of the data will be assumed to be unsigned |
168 | | bytes. This is a "stand-alone" flag constant. It |
169 | | never needs to be '|'d to the others. The exporter|
170 | | will raise an error if it cannot provide such a |
171 | | contiguous buffer of bytes. |
172 | | |
173 +------------------------------+---------------------------------------------------+
174 | :cmacro:`PyBUF_WRITABLE` | The returned buffer must be writable. If it is |
175 | | not writable, then raise an error. |
176 +------------------------------+---------------------------------------------------+
177 | :cmacro:`PyBUF_STRIDES` | This implies :cmacro:`PyBUF_ND`. The returned |
178 | | buffer must provide strides information (i.e. the |
179 | | strides cannot be NULL). This would be used when |
180 | | the consumer can handle strided, discontiguous |
181 | | arrays. Handling strides automatically assumes |
182 | | you can handle shape. The exporter can raise an |
183 | | error if a strided representation of the data is |
184 | | not possible (i.e. without the suboffsets). |
185 | | |
186 +------------------------------+---------------------------------------------------+
187 | :cmacro:`PyBUF_ND` | The returned buffer must provide shape |
188 | | information. The memory will be assumed C-style |
189 | | contiguous (last dimension varies the |
190 | | fastest). The exporter may raise an error if it |
191 | | cannot provide this kind of contiguous buffer. If |
192 | | this is not given then shape will be *NULL*. |
193 | | |
194 | | |
195 | | |
196 +------------------------------+---------------------------------------------------+
197 |:cmacro:`PyBUF_C_CONTIGUOUS` | These flags indicate that the contiguity returned |
198 |:cmacro:`PyBUF_F_CONTIGUOUS` | buffer must be respectively, C-contiguous (last |
199 |:cmacro:`PyBUF_ANY_CONTIGUOUS`| dimension varies the fastest), Fortran contiguous |
200 | | (first dimension varies the fastest) or either |
201 | | one. All of these flags imply |
202 | | :cmacro:`PyBUF_STRIDES` and guarantee that the |
203 | | strides buffer info structure will be filled in |
204 | | correctly. |
205 | | |
206 +------------------------------+---------------------------------------------------+
207 | :cmacro:`PyBUF_INDIRECT` | This flag indicates the returned buffer must have |
208 | | suboffsets information (which can be NULL if no |
209 | | suboffsets are needed). This can be used when |
210 | | the consumer can handle indirect array |
211 | | referencing implied by these suboffsets. This |
212 | | implies :cmacro:`PyBUF_STRIDES`. |
213 | | |
214 | | |
215 | | |
216 +------------------------------+---------------------------------------------------+
217 | :cmacro:`PyBUF_FORMAT` | The returned buffer must have true format |
218 | | information if this flag is provided. This would |
219 | | be used when the consumer is going to be checking |
220 | | for what 'kind' of data is actually stored. An |
221 | | exporter should always be able to provide this |
222 | | information if requested. If format is not |
223 | | explicitly requested then the format must be |
224 | | returned as *NULL* (which means ``'B'``, or |
225 | | unsigned bytes) |
226 +------------------------------+---------------------------------------------------+
227 | :cmacro:`PyBUF_STRIDED` | This is equivalent to ``(PyBUF_STRIDES | |
228 | | PyBUF_WRITABLE)``. |
229 +------------------------------+---------------------------------------------------+
230 | :cmacro:`PyBUF_STRIDED_RO` | This is equivalent to ``(PyBUF_STRIDES)``. |
231 | | |
232 +------------------------------+---------------------------------------------------+
233 | :cmacro:`PyBUF_RECORDS` | This is equivalent to ``(PyBUF_STRIDES | |
234 | | PyBUF_FORMAT | PyBUF_WRITABLE)``. |
235 +------------------------------+---------------------------------------------------+
236 | :cmacro:`PyBUF_RECORDS_RO` | This is equivalent to ``(PyBUF_STRIDES | |
237 | | PyBUF_FORMAT)``. |
238 +------------------------------+---------------------------------------------------+
239 | :cmacro:`PyBUF_FULL` | This is equivalent to ``(PyBUF_INDIRECT | |
240 | | PyBUF_FORMAT | PyBUF_WRITABLE)``. |
241 +------------------------------+---------------------------------------------------+
242 | :cmacro:`PyBUF_FULL_RO`` | This is equivalent to ``(PyBUF_INDIRECT | |
243 | | PyBUF_FORMAT)``. |
244 +------------------------------+---------------------------------------------------+
245 | :cmacro:`PyBUF_CONTIG` | This is equivalent to ``(PyBUF_ND | |
246 | | PyBUF_WRITABLE)``. |
247 +------------------------------+---------------------------------------------------+
248 | :cmacro:`PyBUF_CONTIG_RO` | This is equivalent to ``(PyBUF_ND)``. |
249 | | |
250 +------------------------------+---------------------------------------------------+
Georg Brandl54a3faa2008-01-20 09:30:57 +0000251
252
Benjamin Peterson9d0ced32008-09-16 02:24:31 +0000253.. cfunction:: void PyBuffer_Release(PyObject *obj, Py_buffer *view)
Georg Brandl54a3faa2008-01-20 09:30:57 +0000254
Hirokazu Yamamoto4d4975c2009-03-02 05:49:44 +0000255 Release the buffer *view* over *obj*. This should be called when the buffer
Benjamin Peterson9d0ced32008-09-16 02:24:31 +0000256 is no longer being used as it may free memory from it.
Georg Brandl54a3faa2008-01-20 09:30:57 +0000257
258
Benjamin Peterson9d0ced32008-09-16 02:24:31 +0000259.. cfunction:: Py_ssize_t PyBuffer_SizeFromFormat(const char *)
Georg Brandl54a3faa2008-01-20 09:30:57 +0000260
Benjamin Peterson9d0ced32008-09-16 02:24:31 +0000261 Return the implied :cdata:`~Py_buffer.itemsize` from the struct-stype
262 :cdata:`~Py_buffer.format`.
Georg Brandl54a3faa2008-01-20 09:30:57 +0000263
264
Benjamin Peterson9d0ced32008-09-16 02:24:31 +0000265.. cfunction:: int PyObject_CopyToObject(PyObject *obj, void *buf, Py_ssize_t len, char fortran)
Georg Brandl54a3faa2008-01-20 09:30:57 +0000266
Benjamin Peterson9d0ced32008-09-16 02:24:31 +0000267 Copy *len* bytes of data pointed to by the contiguous chunk of memory pointed
268 to by *buf* into the buffer exported by obj. The buffer must of course be
269 writable. Return 0 on success and return -1 and raise an error on failure.
270 If the object does not have a writable buffer, then an error is raised. If
271 *fortran* is ``'F'``, then if the object is multi-dimensional, then the data
272 will be copied into the array in Fortran-style (first dimension varies the
273 fastest). If *fortran* is ``'C'``, then the data will be copied into the
274 array in C-style (last dimension varies the fastest). If *fortran* is
275 ``'A'``, then it does not matter and the copy will be made in whatever way is
276 more efficient.
Georg Brandl54a3faa2008-01-20 09:30:57 +0000277
278
Benjamin Peterson9d0ced32008-09-16 02:24:31 +0000279.. cfunction:: int PyBuffer_IsContiguous(Py_buffer *view, char fortran)
Georg Brandl54a3faa2008-01-20 09:30:57 +0000280
Benjamin Peterson9d0ced32008-09-16 02:24:31 +0000281 Return 1 if the memory defined by the *view* is C-style (*fortran* is
282 ``'C'``) or Fortran-style (*fortran* is ``'F'``) contiguous or either one
283 (*fortran* is ``'A'``). Return 0 otherwise.
284
285
286.. cfunction:: void PyBuffer_FillContiguousStrides(int ndim, Py_ssize_t *shape, Py_ssize_t *strides, Py_ssize_t itemsize, char fortran)
287
288 Fill the *strides* array with byte-strides of a contiguous (C-style if
289 *fortran* is ``'C'`` or Fortran-style if *fortran* is ``'F'`` array of the
290 given shape with the given number of bytes per element.
291
292
293.. cfunction:: int PyBuffer_FillInfo(Py_buffer *view, void *buf, Py_ssize_t len, int readonly, int infoflags)
294
295 Fill in a buffer-info structure, *view*, correctly for an exporter that can
296 only share a contiguous chunk of memory of "unsigned bytes" of the given
297 length. Return 0 on success and -1 (with raising an error) on error.
298
299
300MemoryView objects
301==================
302
303A memoryview object is an extended buffer object that could replace the buffer
304object (but doesn't have to as that could be kept as a simple 1-d memoryview
305object). It, unlike :ctype:`Py_buffer`, is a Python object (exposed as
306:class:`memoryview` in :mod:`builtins`), so it can be used with Python code.
307
308.. cfunction:: PyObject* PyMemoryView_FromObject(PyObject *obj)
309
310 Return a memoryview object from an object that defines the buffer interface.