索引的 Cython 内存视图应该是 Py_ssize_t 类型还是 int 类型?

Should a Cython memory view of indexes be of type Py_ssize_t or int?

我有一个 cython 代码,它采用 2d numpy.ndarray 数据 (M) 和 numpy.ndarray 索引 (Ixs)。它遍历 Ixs 的条目并使用 Ixs 的值 ix 来索引 M 的列。请看下面的代码:

def foo(double[:, ::1] M, int[:, ::1] Ixs):
    cdef int rows = M.shape[0]
    cdef int cols = M.shape[1]
    cdef Py_ssize_t c, r
    for c in range(rows):
        for r in range(cols):
            ix = Ixs[c, r]
            dosomething(M[c, ix])

我知道我应该使用 Py_ssize_t 作为索引的类型(我读过它是为了适应 64 位架构)但现在我正在使用 [=21 类型的内存视图=]...在这种情况下,我看不到创建 Py_ssize_tnumpy.ndarray 的方法,因此 ixPy_ssize_t.

写这段cython代码的正确方法是什么?使用int有什么问题吗?

有一点需要注意,您需要输入 ix

您编写的代码可以正常工作,M[c, ix] 会将 ix 从 int 转换为 Py_ssize_t,这应该始终是安全的转换。

就是说,您可以并且可能应该将索引器数组设置为 Py_ssize_t。对应的numpy类型为np.intp

https://docs.scipy.org/doc/numpy-1.13.0/user/basics.types.html