Skip to content

Instantly share code, notes, and snippets.

@kwmsmith
Created October 17, 2011 18:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kwmsmith/1293419 to your computer and use it in GitHub Desktop.
Save kwmsmith/1293419 to your computer and use it in GitHub Desktop.
Create NumPy array using data from a C pointer
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