简体   繁体   English

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

[英]Cast part of Ctypes array into structure

I have a big long ctypes array of about 500K uint_32s. 我有一个大的大约500K uint_32s的长ctypes数组。 I want a section from arr[0x4000] to arr[0x8000] to be referenced in a ctypes structure. 我希望在ctypes结构中引用从arr [0x4000]到arr [0x8000]的部分。

Basically: 基本上:

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)

However, doing arr[a,b] turns it from a ctype array to a python list, and I therefore can't use addressof. 但是,执行arr [a,b]会将其从ctype数组转换为python列表,因此我不能使用addressof。

I'm doing it this way becuase I want to be able to do something like: 我这样做是因为我希望能够执行以下操作:

section1.important_thing = 0x12345

and for it to change the raw data in the list, but I don't know exactly how. 并更改列表中的原始数据,但我不知道具体如何。

Thanks for your help. 谢谢你的帮助。

[Python 3.Docs]: ctypes - from_buffer ( source[, offset] ) is what you're looking for. [Python 3.Docs]:ctypes- from_buffersource [,offset]是您想要的。

Example : 范例

 >>> 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) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM