MCPcopy Create free account
hub / github.com/numpy/numpy / PyArray_FromBuffer

Function PyArray_FromBuffer

numpy/core/src/multiarray/ctors.c:3561–3680  ·  view source on GitHub ↗

NUMPY_API*/

Source from the content-addressed store, hash-verified

3559
3560/*NUMPY_API*/
3561NPY_NO_EXPORT PyObject *
3562PyArray_FromBuffer(PyObject *buf, PyArray_Descr *type,
3563 npy_intp count, npy_intp offset)
3564{
3565 PyArrayObject *ret;
3566 char *data;
3567 Py_buffer view;
3568 Py_ssize_t ts;
3569 npy_intp s, n;
3570 int itemsize;
3571 int writeable = 1;
3572
3573 if (type == NULL) {
3574 return NULL;
3575 }
3576
3577 if (PyDataType_REFCHK(type)) {
3578 PyErr_SetString(PyExc_ValueError,
3579 "cannot create an OBJECT array from memory"\
3580 " buffer");
3581 Py_DECREF(type);
3582 return NULL;
3583 }
3584 if (PyDataType_ISUNSIZED(type)) {
3585 PyErr_SetString(PyExc_ValueError,
3586 "itemsize cannot be zero in type");
3587 Py_DECREF(type);
3588 return NULL;
3589 }
3590
3591 /*
3592 * If the object supports `releasebuffer`, the new buffer protocol allows
3593 * tying the memories lifetime to the `Py_buffer view`.
3594 * NumPy cannot hold on to the view itself (it is not an object) so it
3595 * has to wrap the original object in a Python `memoryview` which deals
3596 * with the lifetime management for us.
3597 * For backwards compatibility of `arr.base` we try to avoid this when
3598 * possible. (For example, NumPy arrays will never get wrapped here!)
3599 */
3600 if (Py_TYPE(buf)->tp_as_buffer
3601 && Py_TYPE(buf)->tp_as_buffer->bf_releasebuffer) {
3602 buf = PyMemoryView_FromObject(buf);
3603 if (buf == NULL) {
3604 return NULL;
3605 }
3606 }
3607 else {
3608 Py_INCREF(buf);
3609 }
3610
3611 if (PyObject_GetBuffer(buf, &view, PyBUF_WRITABLE|PyBUF_SIMPLE) < 0) {
3612 writeable = 0;
3613 PyErr_Clear();
3614 if (PyObject_GetBuffer(buf, &view, PyBUF_SIMPLE) < 0) {
3615 Py_DECREF(buf);
3616 Py_DECREF(type);
3617 return NULL;
3618 }

Callers 1

array_frombufferFunction · 0.85

Calls 2

PyArray_CLEARFLAGSFunction · 0.85

Tested by

no test coverage detected