On Friday, May 17, 2013 2:02:42 AM UTC-7, Kevin Kunzmann wrote:
I think I got it working,
cimport cython
import numpy as np
cimport numpy as np
np.import_array()
ctypedef np.float64_t DOUBLE_t
def g():
cdef np.ndarray[DOUBLE_t, ndim=1] A = np.arange(10, dtype=np.float64)
cdef DOUBLE_t* a = <DOUBLE_t*> A.data
cdef np.ndarray[DOUBLE_t, ndim=1] B = np.PyArray_SimpleNewFromData(1, [10], np.NPY_FLOAT64, a)
return B.copy()
My only problem now is that I have to give the type as np.NPY_FLOAT64 explicitely, I tried a ctypedef np.NPY_FLOAT64 C_DOUBLE_t, but that did not work, how do I solve that properly?
The np.NPY_FLOAT64 and similar constants are just integer codes that are meant to be passed to the various NumPy array creation functions. The actual types are np.float64_t, float32_t, etc.
If you just want a memoryview to use within Cython, this should work without copying the data. I'm assuming X_ptr is the 2D C array, with the elements stored row-first, and its size is nrows by ncols.
from numpy cimport float64_t
cdef Py_ssize_t nrows = xxx, ncols = xxx
cdef float64_t [:, ::1] X = <float64_t [:nrows, :ncols]> X_ptr
Note that the memoryview won't free the memory of the underlying C array. You'll have to do that yourself once you're done with it.
Hope that helps.