You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过ctypes正确访问指向其他结构体的结构体指针成员?

问题:在ctypes中访问结构体指针成员时触发AttributeError

场景说明

我需要在Python的ctypes中模拟C语言里all_output_t->input_info->addr的成员访问逻辑,但直接调用buf_obj.input_info.addr时出现错误。

C语言头文件(c_header.h)

typedef struct {
    uint8_t* addr;
    uint32_t size;
    uint8_t id;
} input_info_t;

typedef struct {
    type_t work_type;
    format_t format;
    float runtime;
    /*input*/
    input_info_t *input_info;
    /*output*/
    output_info_t *output_info;
} all_output_t;

对应的ctypes定义(ctypes_header.py)

class input_info_t(ctypes.Structure):
    _fields_ = [
        ('addr', ctypes.POINTER(ctypes.c_uint8)),
        ('size', ctypes.c_uint32),
        ('id', ctypes.c_uint8)
    ]

class output_buffer(ctypes.Structure):
    _fields_ = [
        ('work_type', type_t),
        ('format', format_option),
        ('runtime', ctypes.c_float),
        ('input_info', ctypes.POINTER(input_info_t)),
        ('output_info', ctypes.POINTER(output_info_t))
    ]

错误信息

调用buf_obj.input_info.addr时触发:

Input addr =  <test.common.data_types.LP_input_info object at 0x7fa0ee0140>
Exception ignored on calling ctypes callback function: <function callback_function at 0x7fa111f1f0>
Traceback (most recent call last):
  File "../wrapper.py", line 61, in callback_function
    print('Input buffer length = ', buf_obj.input_info.addr)
AttributeError: 'LP_input_info' object has no attribute 'addr'

解决方案

在ctypes中,结构体指针类型(比如LP_input_info)本身不直接包含结构体成员,需要先通过.contents属性解引用指针,获取其指向的结构体实例后再访问成员。这和C语言中用->解引用指针的逻辑完全对应:

C语法ctypes语法
all_output_t->input_infobuf_obj.input_info(指针对象)
all_output_t->input_info->addrbuf_obj.input_info.contents.addr

正确访问代码示例

# 访问input_info指向的结构体中的addr成员
print('Input addr = ', buf_obj.input_info.contents.addr)
# 访问size成员
print('Input buffer length = ', buf_obj.input_info.contents.size)

额外说明

如果input_info是指向结构体数组的指针,可以直接通过索引访问数组元素,比如:

# 访问数组中第0个元素的addr
buf_obj.input_info[0].addr
# 等价于
buf_obj.input_info.contents.addr

内容的提问来源于stack exchange,提问作者soundarrajan v

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 22:50:36