Created
October 17, 2011 18:42
-
-
Save kwmsmith/1293419 to your computer and use it in GitHub Desktop.
Create NumPy array using data from a C pointer
This file contains hidden or 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
cimport numpy as cnp | |
cimport stdlib | |
cnp.import_array() | |
cdef class _dealloc_obj: | |
cdef void *_data | |
def __cinit__(self): | |
self._data = NULL | |
def __dealloc__(self): | |
if self._data: | |
stdlib.free(self._data) | |
cdef cnp.ndarray np_from_c_data(void *data, int nd, npy_intp *dims, dtype_enum): | |
if data == NULL: | |
raise MemoryError() | |
if nd <= 0: | |
raise ValueError('nd must be >= 0, got %d' % nd) | |
arr = cnp.PyArray_SimpleNewFromData(nd, dims, dtype_enum, data) | |
dobj = _dealloc_obj() | |
dobj.ptr = data | |
cnp.set_array_base(arr, dobj) | |
return arr |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment