[英]ctypes output structure pointer array
I'm trying to wrap an API, that has a lot of functions where it returns a status (no issue there), but the actual output is a structure pointer array.我正在尝试包装一个 API,它有很多返回状态的函数(那里没有问题),但实际的 output 是一个结构指针数组。 I'm having trouble getting a useful structure back.我很难找回一个有用的结构。 All of the documentation I've found so far handles returns instead of pointer outputs.到目前为止,我发现的所有文档都处理返回而不是指针输出。 This is what everything looks like.这就是一切的样子。
foobar.h foobar.h
typedef struct
{
unsigned short serialNumber;
unsigned char ipAddr[4];
} CardInfo;
FOOBARSHARED_EXPORT bool CheckInterfaces( unsigned short someNum, // input
unsigned short *numCards, // output
CardInfo **pCardInfo ); // output
My attempt at wrapping it looks like this:我包装它的尝试如下所示:
foobar.py foobar.py
import ctypes as ct
FOOBAR = ct.CDLL('FOOBAR.dll')
class CardInfo(ct.Structure):
__fields__ = [
('serialNumber', ct.c_ushort),
('ipAddr', ct.c_char*4)
]
def check_interfaces(some_num):
FOOBAR.CheckInterfaces.argtypes = [
ct.c_ushort, ct.POINTER(ct.c_ushort), ct.POINTER(ct.POINTER(CardInfo))
]
FOOBAR.CheckInterfaces.restype = ct.c_bool
num_cards = ct.c_ushort(0)
card_info_pointer = ct.POINTER(CardInfo)()
status = FOOBAR.CheckInterfaces(some_num, ct.byref(num_cards), ct.byref(card_info_pointer))
return [card_info_pointer[i] for i in range(num_cards)]
This does in fact return a list of CardInfo objects, but none of the fields are there.这实际上返回了 CardInfo 对象的列表,但没有任何字段存在。 Any ideas about what I'm missing?关于我所缺少的任何想法?
Try this:尝试这个:
def check_interfaces(some_num):
FOOBAR.CheckInterfaces.restype = ct.c_bool
FOOBAR.CheckInterfaces.argtypes = [
ct.c_ushort,
ct.POINTER(ct.c_ushort),
ct.POINTER(ct.POINTER(CardInfo)),
]
num_cards = ct.c_ushort(0)
card_info_array = (CardInfo * 16)()
status = FOOBAR.CheckInterfaces(some_num, ct.byref(num_cards), ct.byref(card_info_array))
return [card_info_array[i] for i in range(num_cards)]
Thanks to Mark Tolonen 's comment.感谢Mark Tolonen的评论。 I didn't notice that the correct structure field is _fields_
not __fields__
我没有注意到正确的结构字段是_fields_
而不是__fields__
The correct structure should have been:正确的结构应该是:
class CardInfo(ct.Structure):
_fields_ = [
('serialNumber', ct.c_ushort),
('ipAddr', ct.c_char*4)
]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.