Forked from malcolmgreaves/return_memory_as_np_array.pyx
Created
March 4, 2017 00:33
-
-
Save mkolod/64d2f074fbac317192f29eeb4e40b1c6 to your computer and use it in GitHub Desktop.
Take some malloc'd memory, stuff it into a NumPy ndarray so that, when this array is out of scope, the original memory is free'd.
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
import numpy as np | |
cimport numpy as np | |
cdef extern from "numpy/arrayobject.h": | |
void PyArray_ENABLEFLAGS(np.ndarray arr, int flags) | |
object PyArray_SimpleNewFromData(int nd, np.npy_intp* dims, int typenum, void* data) | |
void _import_array() | |
cdef np.ndarray[np.int32_t, ndim=1, mode='c'] from_pointer_to_ndarray(np.npy_intp n_elements, | |
np.int32_t* values): | |
# THIS LINE IS CRITICAL: https://docs.scipy.org/doc/numpy/reference/c-api.array.html#c.import_array | |
_import_array() | |
cdef np.ndarray[np.int32_t, ndim=1, mode='c'] np_values; | |
np_values = np.PyArray_SimpleNewFromData(1, &n_elements, np.NPY_INT32, values) | |
# PyArray_ENABLEFLAGS is *critical* !!! | |
# It ensures that, when this ndarray goes out of scope, the underlying array's memory | |
# is free'd (aka our np.int32_t* community is free'd). | |
PyArray_ENABLEFLAGS(np_values, np.NPY_OWNDATA) | |
return np_values |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment