[英]Is there a reason why Python's ctypes.CDLL cannot automatically generate restype and argtypes from C header files?
[英]How to determine Python3 ctypes .argtypes from C function signature?
我正在為第 3 方 DLL 編寫 ctypes 接口(我無法控制 DLL)。
我的代碼似乎有效,但我擔心我設置.argtypes
錯誤。
我試圖調用的 C function 的簽名是:
int GetData(unsigned short option, unsigned char* buffer, int bufferLength, int &actualLength);
option
指示請求的數據類型, buffer
指向我提供的緩沖區, bufferLength
是緩沖區的長度(以字節為單位)。
DLL function 寫入緩沖區,並將它實際寫入的字節數放入actualLength
。
我的代碼:
import ctypes
dll = ctypes.CDLL("dll_name.dll")
def GetData(option):
BUFSIZE = 6
buf = bytearray(BUFSIZE)
ptr_to_buf = (ctypes.c_char*len(buf)).from_buffer(buf)
actualLength = ctypes.c_int()
dll.GetData.argtypes = (ctypes.c_ushort,
ctypes.c_char_p,
ctypes.c_int,
ctypes.POINTER(ctypes.c_int))
dll.GetData.restype = int
dll.GetData(option,
ptr_to_buf,
BUFSIZE,
ctypes.byref(actualLength))
return (buf, actualLength.value)
對GetData()
的調用是否准確反映了 .argtypes?
ptr_to_buf
作為ctypes.c_char_p
傳遞嗎?ctypes.POINTER
傳遞給ctypes.byref
嗎?.pointer
而不是.byref?
我確實閱讀了 ctype 文檔,我知道他們說.byref
更快,但我不清楚何時需要.pointer
。 .argtypes
很好。 您可能希望POINTER(c_ubyte)
完全同意原型,但c_char_p
通常更易於使用。
- 可以像我在這里做的那樣將 ptr_to_buf 作為 ctypes.c_char_p 傳遞嗎?
是的。 數組作為相同元素類型的指針傳遞。
- 可以像我在這里做的那樣將 ctypes.byref 傳遞給 ctypes.POINTER 嗎?
是的。
- 什么時候需要使用.pointer 而不是.byref? 我確實閱讀了 ctype 文檔,我知道他們說.byref 更快,但我不清楚何時需要.pointer。
當你需要一個具體的指針時創建一個pointer
。 我很少使用pointer
。 假設您在 C 中有此代碼,並且有一些理由模仿它:
int x = 5;
int* y = &x;
Python 等效項為:
x = c_int(5)
y = pointer(x)
- 還有什么我做錯了嗎?
.restype
應該有一個ctype
類型。 .restype = c_int
是正確的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.