Python 如何在cython中从c数组公开numpy数组?

Python 如何在cython中从c数组公开numpy数组?,python,numpy,cython,Python,Numpy,Cython,我希望它返回一个numpy数组。我怎么做 现在我必须做些什么 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

我希望它返回一个numpy数组。我怎么做

现在我必须做些什么

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

在这里的
memview
示例中

我可以从
carr\u视图
中创建一个numpy数组,
carr
上的内存视图,一个C数组

# Memoryview on a C array
cdef int carr[3][3][3]
cdef int [:, :, :] carr_view = carr
carr_view[...] = narr_view  # np.arange(27, dtype=np.dtype("i")).reshape((3, 3, 3))
carr_view[0, 0, 0] = 100

如果您只是在函数中声明数组,为什么不首先将其设置为numpy数组,那么当您需要c数组时,只需获取数据指针即可

# print np.array(carr)    # cython error
print 'numpy array on carr_view'
print np.array(carr_view)
print np.array(carr_view).sum()   # match sum3d(carr)
# or np.asarray(carr_view)


print 'numpy copy from carr_view'
carr_copy = np.empty((3,3,3))
carr_copy[...] = carr_view[...]  # don't need indexed copy
print carr_copy
print carr_copy.sum()   # match sum3d(carr)
我打错了字,
ret=np.asarray(pd_视图)

# print np.array(carr)    # cython error
print 'numpy array on carr_view'
print np.array(carr_view)
print np.array(carr_view).sum()   # match sum3d(carr)
# or np.asarray(carr_view)


print 'numpy copy from carr_view'
carr_copy = np.empty((3,3,3))
carr_copy[...] = carr_view[...]  # don't need indexed copy
print carr_copy
print carr_copy.sum()   # match sum3d(carr)
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