如何为指向指针的指针配置argtypes?附C与Python代码示例
如何为指向指针的指针配置argtypes?
可正常运行的C代码示例
bool GetDeviceList(unsigned short **DevLists, int *DevCnt); unsigned short *DevLists[260 * 12]; int DevCnt; bool ret = GetDeviceList(DevLists, &DevCnt);
我的Python尝试代码
mydll = CDLL(dll_path) mydll.GetDeviceList.argtypes = [POINTER(c_ushort*260), POINTER(c_int)] mydll.GetDeviceList.restype = c_bool wsList = (c_ushort*260*12)() RetNum = c_int() ret = mydll.GetDeviceList(wsList,byref(RetNum))
正确的argtypes配置方法
C代码里的unsigned short **DevLists实际接收的是存放unsigned short*的数组,对应到ctypes里,你需要用POINTER(POINTER(c_ushort))来匹配这个类型。如果要更贴合代码里固定大小的数组定义,也可以用POINTER(POINTER(c_ushort) * (260*12)),通用场景下前者足够。
另外要注意:你创建的(c_ushort*260*12)()是二维数组,和C里的unsigned short *DevLists[260*12](指针数组)不是同一类型,正确的指针数组创建方式如下:
from ctypes import * mydll = CDLL(dll_path) # 匹配unsigned short**的argtypes配置 mydll.GetDeviceList.argtypes = [POINTER(POINTER(c_ushort)), POINTER(c_int)] mydll.GetDeviceList.restype = c_bool # 创建可容纳260*12个unsigned short指针的数组 DevLists = (POINTER(c_ushort) * (260*12))() DevCnt = c_int() ret = mydll.GetDeviceList(DevLists, byref(DevCnt))
如果C函数会为DevLists里的每个指针分配内存,后续要根据DLL的内存管理规则,调用对应的释放函数清理内存。
如果每个unsigned short*固定指向长度为260的数组,也可以用更精确的定义:
# 每个元素是指向260个c_ushort的指针 DevLists = (POINTER(c_ushort * 260) * (260*12))() # 对应的argtypes也可以同步调整 mydll.GetDeviceList.argtypes = [POINTER(POINTER(c_ushort * 260)), POINTER(c_int)]
这样配置后就能准确适配C函数的unsigned short**参数类型。
内容的提问来源于stack exchange,提问作者Kobe Nein
相关产品推荐
相关产品推荐

