将 Ctypes 数组的一部分转换为结构

Cast part of Ctypes array into structure

我有一个大约 500K 的大长 ctypes 数组 uint_32s。我想在 ctypes 结构中引用从 arr[0x4000] 到 arr[0x8000] 的部分。

基本上:

class my_struct(Structure):
    _fields_ = [
        (important_thing, c_uint32*128),
        (other_thing, c_uint32*16) #etc. etc.
    ]

#arr is a huge ctypes array of length 500K made up of uint_32
section1 = cast(addressof(arr[0x4000:0x8000]),POINTER(my_struct)

但是,执行 arr[a,b] 会将其从 ctype 数组转换为 python 列表,因此我不能使用 addressof。

我这样做是因为我希望能够做类似的事情:

section1.important_thing = 0x12345

并让它改变列表中的原始数据,但我不知道具体如何。

感谢您的帮助。

[Python 3.Docs]: ctypes - from_buffer(source[, offset]) 就是您要找的。

示例

>>> import ctypes
>>>
>>> class Struct0(ctypes.Structure):
...     _fields_ = [
...         ("important", ctypes.c_uint32 * 128),
...         ("other", ctypes.c_uint32 * 16),  # Other fields
...     ]
...
>>>
>>> arr = (ctypes.c_uint32 * 0x200)(*range(0x0200))  # Array filled with values [0 .. 511]
>>> arr[0x0001], arr[0x0100], arr[0x01FF]
(1, 256, 511)
>>>
>>> s0 = Struct0.from_buffer(arr, 0x0100 * ctypes.sizeof(ctypes.c_uint32))  # Start from 257th element (index 256)
>>>
>>> s0.important[0x0000], s0.important[0x007F]  # Struct0.important first and last elements
(256, 383)