python - 如何在 cython 中从 c 数组公开一个 numpy 数组?

标签 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

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

目前我要做的

pd_np = np.zeros(8000, dtype=np.double)
cdef int i
for i in range(8000):
    pd_np[i] = pd[i]

最佳答案

如果你只是在你的函数中声明你的数组为什么不让它成为一个 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

关于python - 如何在 cython 中从 c 数组公开一个 numpy 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29036068/

相关文章:

python - 仅在我的两个相同网站之一上出现导入错误

python - pandas 中的并行字符串替换

python - 将 NumPy 字符串数组映射为整数

python - 如何在整个 numpy 矩阵中获取最大(顶部)N 个值

python - 数组的 cython/numpy 类型

python - cimport 给出 fatal error : 'numpy/arrayobject.h' file not found

python - 如何将静态成员添加到 Cython 类(来自 python,而不是 C)

python - 将 "Quoted-printable"编码改为 "utf-8"

python - Bokeh :添加/删除面板,同时保留当前面板

python - numpy 选择每隔 n 个条目