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

Function array_dlpack

numpy/core/src/multiarray/dlpack.c:122–277  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

120
121
122PyObject *
123array_dlpack(PyArrayObject *self,
124 PyObject *const *args, Py_ssize_t len_args, PyObject *kwnames)
125{
126 PyObject *stream = Py_None;
127 NPY_PREPARE_ARGPARSER;
128 if (npy_parse_arguments("__dlpack__", args, len_args, kwnames,
129 "$stream", NULL, &stream, NULL, NULL, NULL)) {
130 return NULL;
131 }
132
133 if (stream != Py_None) {
134 PyErr_SetString(PyExc_RuntimeError,
135 "NumPy only supports stream=None.");
136 return NULL;
137 }
138
139 if ( !(PyArray_FLAGS(self) & NPY_ARRAY_WRITEABLE)) {
140 PyErr_SetString(PyExc_BufferError,
141 "Cannot export readonly array since signalling readonly "
142 "is unsupported by DLPack.");
143 return NULL;
144 }
145
146 npy_intp itemsize = PyArray_ITEMSIZE(self);
147 int ndim = PyArray_NDIM(self);
148 npy_intp *strides = PyArray_STRIDES(self);
149 npy_intp *shape = PyArray_SHAPE(self);
150
151 if (!PyArray_IS_C_CONTIGUOUS(self) && PyArray_SIZE(self) != 1) {
152 for (int i = 0; i < ndim; ++i) {
153 if (shape[i] != 1 && strides[i] % itemsize != 0) {
154 PyErr_SetString(PyExc_BufferError,
155 "DLPack only supports strides which are a multiple of "
156 "itemsize.");
157 return NULL;
158 }
159 }
160 }
161
162 DLDataType managed_dtype;
163 PyArray_Descr *dtype = PyArray_DESCR(self);
164
165 if (PyDataType_ISBYTESWAPPED(dtype)) {
166 PyErr_SetString(PyExc_BufferError,
167 "DLPack only supports native byte order.");
168 return NULL;
169 }
170
171 managed_dtype.bits = 8 * itemsize;
172 managed_dtype.lanes = 1;
173
174 if (PyDataType_ISBOOL(dtype)) {
175 managed_dtype.code = kDLBool;
176 }
177 else if (PyDataType_ISSIGNED(dtype)) {
178 managed_dtype.code = kDLInt;
179 }

Callers

nothing calls this directly

Calls 8

PyArray_FLAGSFunction · 0.85
PyArray_ITEMSIZEFunction · 0.85
PyArray_NDIMFunction · 0.85
PyArray_STRIDESFunction · 0.85
PyArray_SHAPEFunction · 0.85
PyArray_DESCRFunction · 0.85
array_get_dl_deviceFunction · 0.85
PyArray_DATAFunction · 0.85

Tested by

no test coverage detected