[問題] ctypes 如何處理回傳可能為NULL的函式?

作者: wtchen (沒有存在感的人)   2017-07-08 23:32:00
最近用ctypes寫一個wrapper去使用用C開發的DLL。
有一個函式是這樣:
struct __abc
{
int8_t a;
.... (其他參數省略)
struct __abc* next;
} ;
然後
typedef struct __abc* ABC;
這個函式大概長這樣:
ABC GetNext(ABC x)
{
return x->next; // 可以為NULL或這個linked list的下個元素
}
用ctypes包裝的時候是這樣:
_GetNext = _lib.GetNext
_GetNext.argtype = [ABC]
_GetNext.restype = ABC
結果我發現,如果執行的時候回傳時剛好為NULL python就會出問題。
OSError: exception: access violation writing 0x00000000
請問可以怎麼解決?
感謝。
作者: uranusjr (←這人是超級笨蛋)   2017-07-09 00:11:00
你傳 ABC x 為什麼裡面 next 是當 pointer 用這樣應該是你 Python 側的 ABC 宣告方法有問題, 正常來說 null pointer 應該會被轉換成 None 才對如果是 opaque pointer 就直接用 c_void_p不然你就要手動檢查, 直接把 pointer 轉 bool (False 代next = _GetNext(x); if next: print('Not null')大概像上面這樣
作者: wtchen (沒有存在感的人)   2017-07-09 01:54:00
原來如此。謝謝。
作者: ny8426 (kerker)   2017-07-09 10:11:00

Links booklink

Contact Us: admin [ a t ] ucptt.com