Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save mkolod/64d2f074fbac317192f29eeb4e40b1c6 to your computer and use it in GitHub Desktop.
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.
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