如何访问在 cython 中声明的 class 的类型化内存视图元素?

How to access the typed-memory view element of a class declared in cython?

我是初学者,我觉得这个问题太简单了。我正在尝试在 cython 中测试内存视图以更多地了解它们 better.In 我的代码我将每个内存视图元素(如 [1,2])作为 cy class 元素传递 move.

cdef class cy:
    cdef public long[:] move
    def __init__(self, move):
        self.move = move
lst = []
for i in range(100):
    lst.append([i, i+1])

cdef long[:, :] memview = np.asarray(lst)

b0 = cy(memview[0])
print(b0.move)

当我打印结果时。我明白了:

<MemoryView of 'ndarray' object> # I expect for sth like [12, 13]

我需要cy class打印出一个列表。我该如何解决? 当我使用这段代码时,我遇到了另一个问题:

cdef class parent:
    cdef public:
        list children
        list moves
    def __init__(self):
        self.children = []
    def add_children(self, moves):
        cdef int i = 0
        cdef int N = len(moves)
        for i in range(N):
            self.children.append(cy(moves[i]))

cdef int[:, :] moves = np.asarray(lst, dtype=np.int32)
obj = parent()

for move in moves:
    obj.add_children(move)

在 运行 这段代码之后我总是得到这个错误:
TypeError: a bytes-like object is required, not 'int'。 导致此错误的原因是什么?我该如何解决?

您的第一个问题只是内存视图没有有用的 __str__ 函数供打印使用。您可以将其转换为打印效果很好的对象

print(list(b0.moves))
print(np.asarray(b0.moves))

或者您可以自己遍历它:

for i in range(b0.moves.shape[0]):
    print(b0.moves[i], end=' ') # need to have Cython set to use Python 3 syntax for this line
print()

你的第二个问题比较难解决,因为你没有告诉我们错误来自哪一行。我认为这是 cy 的构造函数,它需要一个内存视图,但你传递了一个整数。 (不过我收到的错误消息略有不同)。