【发布时间】:2022-01-17 00:21:20
【问题描述】:
我有一个 c++ API 函数,我需要使用 ctypes 从 python 调用它。
在我的 c++ libamo.h 中,我有 struct 和 function 的原型,如下所示,
typedef struct contain_t
{
uint8_t id;
uint16_t ele1;
uint16_t ele2;
uint16_t ele3;
uint16_t ele4;
float ele5;
} mycontain;
mycontain* get_result(void *context, int r, int c, unsigned char* rawdata);
在我的 c++ libamo.cpp 中,
我已经声明了结构的全局数组,
mycontain all_contain[50];
函数mycontain* get_result() 填充结构数组,我已经在 c++ 中通过打印结构的内容对其进行了测试。
在ctypes:
- 正在加载
libamo.so。 - 将结构模板定义为,
from ctypes import *
class mycontain(Structure):
_fields_ = [('id', c_uint),
('ele1',c_uint),
('ele2', c_uint),
('ele3', c_uint),
('ele4', c_uint),
('ele5', c_float) ]
ptr_cnt = POINTER(mycontain)
amo_get_result = libamo.get_result
amo_get_result.restype = ptr_cnt
amo_get_result.argtypeps = [c_void_p, c_int, c_int, c_char_p]
res = amo_get_result(amo_context, 300, 300, raw_val.ctypes.data_as(c_char_p))
我尝试了以下方法从结构成员中获取数据。
方法一:
output_res = res.contents
print(output_res.id, output_res.ele1, output_res.ele2, output_res.ele3, output_res.ele4, output_res.ele5)
对于上述元素,我得到的输出
7208960 0.0 4128919 173 1049669215 21364736
方法2:尝试投射
print(cast(output_res.id, POINTER(c_uint)))
output>><__main__.LP_c_uint object at 0x7f9450f3c0>
我的问题是, - 如何优雅地从结构数组中读取数据。我参考了多个 SO 帖子,大多数讨论的是访问单个结构实例的方法,而不是结构数组。
【问题讨论】: