import numpy as np
cimport numpy as np
np.import_array()
cimport cython
from libc.stdlib cimport malloc, free
cdef extern from "numpy/arrayobject.h":
void PyArray_ENABLEFLAGS(np.ndarray arr, int flags)
cdef view_to_ndarray(view):
arr = np.asarray(view)
PyArray_ENABLEFLAGS(arr, np.NPY_OWNDATA)
return arr
cdef pointer_to_ndarray(void * ptr, np.npy_intp nbyte):
arr = np.PyArray_SimpleNewFromData(1, &nbyte, np.NPY_BYTE, ptr)
PyArray_ENABLEFLAGS(arr, np.NPY_OWNDATA)
return arr
cdef void * ndarray_to_pointer(np.ndarray arr):
assert arr.flags.c_contiguous
cdef np.npy_byte[::1] view=arr.view('byte').reshape(-1)
cdef void * ptr = <void *> &view[0]
return ptr
cdef:
np.npy_intp m=64, nbytes
np.npy_byte* ptr
nbytes = sizeof(np.npy_byte) * m
ptr = <np.npy_byte*> malloc(nbytes)
arr = pointer_to_ndarray(<void *>ptr, nbytes).view('f8')
print <long long>(ptr)
ptr = <np.npy_byte*> ndarray_to_pointer(arr)
print <long long>(ptr)
cdef:
int n=8
float[:,:] view
view = <float[:n, :3]> malloc(sizeof(float) * n * 3)
arr2 = view_to_ndarray(view)