为了账号安全,请及时绑定邮箱和手机立即绑定

如何使用 cpython 将结构数组传递给 DLL 函数?

如何使用 cpython 将结构数组传递给 DLL 函数?

临摹微笑 2022-05-11 15:24:34
#include <stdio.h>struct struct_data {    int price;    char list[255];    int count;};__declspec(dllexport) void __stdcall testcall(struct struct_data *array_data) {    int i = 0;    while(array_data[i].price != 0) {           // array_data is guaranteed to have a zero somewhere inside memory allocated for the array        printf("%d\n", array_data[i].price);        i++;    }}我尝试使用 cpython 从 Python 调用它,如下所示:# C Backend importsimport osimport sysimport ctypes# load DLLdll = ctypes.WinDLL('C:\\Users\\user\Documents\\Pelles C Projects\\MarketlibDLL\\MarketlibDLL.dll')class struct_data(ctypes.Structure):    _fields_ = [        ('price', ctypes.c_int),        ('list', ctypes.c_char * 255),        ('count', ctypes.c_int),    ]d = struct_data() * 100    # I try to do:   struct struct_data d[100]; d[0].price = 100d[0].list = "ABC"d[0].count = 3d[1].price = 0dll.testcall.argtypes = [ctypes.POINTER(struct_data)]dll.testcall(d)---------------------------------------------------------------------------TypeError                                 Traceback (most recent call last)<ipython-input-2-36161e840b5f> in <module>----> 1 d = struct_data() * 100      2 d[0].price = 100      3 d[0].list = "ABC"      4 d[0].count = 3      5 d[1].price = 0TypeError: unsupported operand type(s) for *: 'struct_data' and 'int'
查看完整描述

2 回答

?
慕容3067478

TA贡献1773条经验 获得超3个赞

[Python 3.Docs]:ctypes - Python 的外部函数库具有所有必需的信息(数组部分包含一个完美映射当前场景的示例)。


将您的代码修改为(为了便于阅读,分成两行):


struct_data_array_100 = struct_data * 100  # !!! This is a type (array consisting of 100 struct_data elements) !!!

d = struct_data_array_100()  # Instantiate the array type

#d[0].price ...

# ...


查看完整回答
反对 回复 2022-05-11
?
Smart猫小萌

TA贡献1911条经验 获得超7个赞

如果你想要一个 100 的列表,struct_data你需要将列表而不是数据相乘:

d = [struct_data()] * 100

这和写法一样:

d = [struct_data() for _ in range(100)]


查看完整回答
反对 回复 2022-05-11
  • 2 回答
  • 0 关注
  • 188 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信