-
-
Save kynan/ade36155b497c87e0bc5 to your computer and use it in GitHub Desktop.
Create NumPy array from ptr and take ownership of the data
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ cython /tmp/test.pyx | |
Error compiling Cython file: | |
------------------------------------------------------------ | |
... | |
void PyArray_ENABLEFLAGS(np.PyArrayObject *arr, int flags) | |
cdef data_to_numpy_array_with_spec(void * ptr, np.npy_intp size, int t): | |
"""Return an array of SIZE elements (each of type T) with data from PTR.""" | |
cdef np.ndarray[DTYPE_t, ndim=1] arr = np.PyArray_SimpleNewFromData(1, &size, t, ptr) | |
PyArray_ENABLEFLAGS(arr, np.NPY_ARRAY_OWNDATA) | |
^ | |
------------------------------------------------------------ | |
/tmp/test.pyx:17:27: Cannot convert Python object to 'PyArrayObject *' |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Create NumPy array from ptr and take ownership of the data | |
from libc.stdlib cimport malloc | |
import numpy as np | |
cimport numpy as np | |
np.import_array() | |
ctypedef np.int32_t DTYPE_t | |
cdef extern from "numpy/ndarraytypes.h": | |
void PyArray_ENABLEFLAGS(np.PyArrayObject *arr, int flags) | |
cdef data_to_numpy_array_with_spec(void * ptr, np.npy_intp size, int t): | |
"""Return an array of SIZE elements (each of type T) with data from PTR.""" | |
cdef np.ndarray[DTYPE_t, ndim=1] arr = np.PyArray_SimpleNewFromData(1, &size, t, ptr) | |
PyArray_ENABLEFLAGS(arr, np.NPY_ARRAY_OWNDATA) | |
return arr | |
def test(): | |
N = 1000 | |
cdef DTYPE_t *data = <DTYPE_t *>malloc(N * sizeof(DTYPE_t)) | |
arr = data_to_numpy_array_with_spec(data, N, np.NPY_INT32) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment