col*_*ang 5 python numpy cython
cpdef myf():
# pd has to be a c array.
# Because it will then be consumed by some c function.
cdef double pd[8000]
# Do something with pd
...
# Get a memoryview.
cdef double[:] pd_view = pd
# Coercion the memoryview to numpy array. Not working.
ret = np.asarray(pd)
return ret
Run Code Online (Sandbox Code Playgroud)
我希望它返回一个numpy数组.我该怎么做?
目前我必须这样做
pd_np = np.zeros(8000, dtype=np.double)
cdef int i
for i in range(8000):
pd_np[i] = pd[i]
Run Code Online (Sandbox Code Playgroud)
如果只是在函数中声明数组,为什么不使其成为一个numpy数组,那么当您需要c数组时,只需获取数据指针即可。
cimport numpy as np
import numpy as np
def myf():
cdef np.ndarray[double, ndim=1, mode="c"] pd_numpy = np.empty(8000)
cdef double *pd = &pd_numpy[0]
# Do something to fill pd with values
for i in range(8000):
pd[i] = i
return pd_numpy
Run Code Online (Sandbox Code Playgroud)