作者wtchen (沒有存在感的人)
看板Python
標題[問題] ctypes 如何處理回傳可能為NULL的函式?
時間Sat Jul 8 23:32:00 2017
最近用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
請問可以怎麼解決?
感謝。
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 90.27.156.252
※ 文章網址: https://webptt.com/m.aspx?n=bbs/Python/M.1499527922.A.535.html
1F:→ uranusjr: 你傳 ABC x 為什麼裡面 next 是當 pointer 用 07/09 00:11
※ 編輯: wtchen (90.27.156.252), 07/09/2017 00:50:39
抱歉,ABC應該是 struct __abc的pointer,已修正
※ 編輯: wtchen (90.27.156.252), 07/09/2017 00:51:06
2F:→ uranusjr: 這樣應該是你 Python 側的 ABC 宣告方法有問題, 正常來 07/09 01:14
3F:→ uranusjr: 說 null pointer 應該會被轉換成 None 才對 07/09 01:14
因為__abc的實作是被藏起來沒含在header裡,所以在python我這樣做:
class __abc(Structure):
pass
ABC = POINTER(__abc)
不知道這樣對不對就是了....
※ 編輯: wtchen (90.27.156.252), 07/09/2017 01:22:40
※ 編輯: wtchen (90.27.156.252), 07/09/2017 01:23:54
4F:→ uranusjr: 如果是 opaque pointer 就直接用 c_void_p 07/09 01:46
5F:→ uranusjr: 不然你就要手動檢查, 直接把 pointer 轉 bool (False 代 07/09 01:49
6F:→ uranusjr: next = _GetNext(x); if next: print('Not null') 07/09 01:50
7F:→ uranusjr: 大概像上面這樣 07/09 01:50
8F:→ wtchen: 原來如此。謝謝。 07/09 01:54
9F:推 ny8426: 推 07/09 10:11