Skip to content

Instantly share code, notes, and snippets.

@kynan
Created May 7, 2014 16: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 kynan/ade36155b497c87e0bc5 to your computer and use it in GitHub Desktop.
Save kynan/ade36155b497c87e0bc5 to your computer and use it in GitHub Desktop.
Create NumPy array from ptr and take ownership of the data
$ 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 *'
# 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