【发布时间】:2021-04-27 23:15:15
【问题描述】:
我正在为第 3 方 DLL 编写 ctypes 接口(我无法控制 DLL)。
我的代码似乎可以工作,但我担心我设置 .argtypes 错误。
我试图调用的 C 函数的签名是:
int GetData(unsigned short option, unsigned char* buffer, int bufferLength, int &actualLength);
option 表示请求的数据类型,buffer 指向我提供的缓冲区,bufferLength 是缓冲区的长度(以字节为单位)。
DLL 函数写入缓冲区,并将它实际写入的字节数放入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.byref传递到ctypes.POINTER吗? - 什么时候需要使用
.pointer而不是.byref?我确实阅读了ctype 文档,我知道他们说.byref更快,但我不清楚何时需要.pointer。 - 还有什么我做错了吗?
【问题讨论】:
-
这一切都很好。用
c_void_p代替c_char_p可能会更自然一些,但是净效果应该是一样的,所以我就不去碰了。
标签: python python-3.x ctypes