[英]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.