[英]How to check whether a memmoryview in Null in cython
我想檢查 memory 視圖是否被初始化為 None。 我有一個像這樣的 function:
cdef void test(int[:] a):
if a == NULL:
print("invalid data")
cdef int[:] memview = None
test(memview)
編譯時出現此錯誤:
Invalid types for '==' (int[:], void *)
將 None 分配給內存視圖是否存在問題? 如果不是這種情況,我該怎么做才能檢測 NULL 值?
謝謝!
將我的評論變成一個非常好的答案:
您正在將None
分配給您的 memoryview:
cdef int[:] memview = None
因此,檢查它是有意義的None
,而不是NULL
:
if a is None:
Ultimately they're similar concepts but different things: NULL
is a pointer that doesn't point to anything, while None
is a singleton Python object that indicates that something is unset. C 級別和 Python 級別之間的區別實際上是“Python 級別”。
如果nogil
塊中if a is None
,還有一個額外的細節可以讓您執行: Python 確保存在恰好一個None
object (並且對於整個程序,它保持相同的None
ZA8CFDE6331BD59EB2AC96F8911C4B666) 因此可以將a is None
轉換為 C 代碼
((PyObject *) __pyx_v_a.memview) == Py_None
即一個簡單的指針比較,不需要 GIL,因為引用計數沒有變化。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.