Ctypes:获取指向结构字段的指针 [英] Ctypes: Get a pointer to a struct field

查看:253
本文介绍了Ctypes:获取指向结构字段的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要获取一个带有struct字段地址的指针. 重要:我正在为一组c结构构建一个序列化程序,因此我想遍历一个结构的字段并获取它们每个的地址作为指针. 我知道有一种使用字段对象和它们的offset属性的方法,可以为您提供与结构本身地址的偏移量,但这是一个通用指针. 您能告诉我一种如何遍历struct字段的方法,并且为每个字段获取一个带有正确内部类型的ctypes指针吗?

I need to get a pointer with the address of a struct field. Important: I'm builduing a serializer for a set of c structs so i want to iterate over the fields of a struct and get the address of each of them as a pointer. I know there is a way using fields object and offset property of them which is giving you the offset from the address of the structure itself but it is a generic pointer. Could you show me a way on how to iterate over struct fields and for each of them get a ctypes pointer with a correct inner type?

推荐答案

这是一种方法...

类变量Test._fields_定义属性及其C类型.通过分配字段生成的类属性包含有关该属性的偏移量的信息,例如:

The class variable Test._fields_ defines the attributes and their C types. The class attributes generated by assigning the fields contain information about the offset for that attribute, for example:

>>> Test.a
<Field type=c_long, ofs=0, size=4>
>>> Test.b
<Field type=c_double, ofs=8, size=8>
>>> Test.c
<Field type=c_char_Array_10, ofs=16, size=10>

对于每种类型,from_buffer()方法使用与现有类型相同的数据缓冲区来构建C类型.结构的实例实现了访问其数据所需的缓冲区API,因此,如果您知道结构元素的数据的偏移量,则可以生成引用相同数据的ctypes类型,并创建指向该数据的指针.

For each type, the from_buffer() method builds a C type using the same data buffer as an existing type. An instance of the structure implements the buffer API required to access its data, so if you know the offset of a structure element's data, you can generate a ctypes type that references the same data, and create a pointer to it.

from ctypes import *

class Test(Structure):
    _fields_ = [('a',c_int),
                ('b',c_double),
                ('c',c_char * 10)]

x = Test(1,2.5,b'abc')

for field,ftype in Test._fields_:

    # Look up each attribute in the class, and get its offset.
    ofs = getattr(Test,field).offset

    # Create a pointer to the same field type using the same data.
    p = pointer(ftype.from_buffer(x,ofs))
    print(p,p.contents)

输出:

<__main__.LP_c_long object at 0x000001932DE0EEC8> c_long(1)
<__main__.LP_c_double object at 0x000001932DE0ECC8> c_double(2.5)
<__main__.LP_c_char_Array_10 object at 0x000001932DE0EDC8> <__main__.c_char_Array_10 object at 0x000001932DE0ECC8>

这篇关于Ctypes:获取指向结构字段的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆