Cython:`numpy` 数组的内存视图丢失了 `numpy` 数组特性?

Cython: memory views on `numpy` arrays lose `numpy` array features?

考虑以下示例:

cdef test_function():
    cdef:
        double[:] p1 = np.array([3.2, 2.1])
        double[:] p2 = np.array([0.9, 6.])

    return p1-p2

如果使用,会returns出现以下错误:

Error compiling Cython file:
------------------------------------------------------------
...
cdef test_function():
    cdef:
        double[:] p1 = np.array([3.2, 2.1])
        double[:] p2 = np.array([0.9, 6.])

    return p1-p2
            ^
------------------------------------------------------------

cython_cell_v3.pyx:354:13: Invalid operand types for '-' (double[:]; double[:])

如果我使用 numpy 数组来初始化内存视图,我该如何使用它的功能?我是否必须以某种方式对内存视图进行一些取消引用?

这个有效:

cpdef test_function():
    cdef:
        double[:] p1 = np.array([3.2, 2.1])
        double[:] p2 = np.array([0.9, 6.])

    # return p1-p2
    cdef int I
    I = p1.shape[0]
    for i in range(I):
        p1[i] -= p2[i]
    return np.asarray(p1)
print "Test _function", test_function()

我在数组上进行迭代,就好像它们是 'c' 数组一样。如果没有最后的 np.asarray,它只会显示

>>> memview.test_function()
<MemoryView of 'ndarray' at 0xb60e772c>

另见示例 http://docs.cython.org/src/userguide/memoryviews.html#comparison-to-the-old-buffer-support


我尝试了不同的功能:

cpdef test_function1(x):
    cdef:
        int i, N = x.shape[0]
        double[:] p1 = x
    for i in range(N):
        p1[i] *= p1[i]
    return np.asarray(p1)*2

x = np.arange(10.)
print "test_function1 return", test_function1(x)
print "x after test_function1", x

不出所料,函数x之后就是x**2。但是函数 returns 是什么 2*x**2.

我直接修改了p1,结果也修改了x。我认为 p1x 的视图,但功能有所减少。 np.asarray(p1) 赋予它 numpy 功能,因此我可以对其执行数组 * 和 return 结果(无需进一步修改 x)。

如果我用以下方法完成函数:

out = np.asarray(p1)
out *= 2
return out 

我最终也修改了原来的 xoutx 上的一个 numpy 视图。 out 表现得像一个数组,因为它是一个,而不是因为 link 到 x.