看板 Python 關於我們 聯絡資訊
最近用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://www.ptt.cc/bbs/Python/M.1499527922.A.535.html
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
uranusjr: 這樣應該是你 Python 側的 ABC 宣告方法有問題, 正常來 07/09 01:14
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
uranusjr: 如果是 opaque pointer 就直接用 c_void_p 07/09 01:46
uranusjr: 不然你就要手動檢查, 直接把 pointer 轉 bool (False 代 07/09 01:49
uranusjr: next = _GetNext(x); if next: print('Not null') 07/09 01:50
uranusjr: 大概像上面這樣 07/09 01:50
wtchen: 原來如此。謝謝。 07/09 01:54
ny8426: 推 07/09 10:11