![](/img/trans.png)
[英]Cython extension type method with typed-memory-view as argument
[英]How to access the typed-memory view element of a class declared in cython?
我是一個初學者,我相信這個問題太簡單了。 我試圖在cython中測試內存視圖,以更好地了解它們。在我的代碼中,隨着cy
類元素的move
我傳遞了每個內存視圖元素(例如[1,2]
)。
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
類打印出一個列表。 我該如何解決? 使用此代碼時,我會遇到另一個問題:
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'
。 是什么導致此錯誤,我該如何解決?
您的第一個問題是memoryview沒有有用的__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
的構造函數,需要一個memoryview,但是您將一個整數傳遞給了。 (不過,我得到的錯誤消息略有不同)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.