我有一个 Ctypes 结构,它需要以易于实现的标准方式 [setattr(structure,value)] 进行编辑,但我还需要能够编辑原始缓冲区,因为我希望能够分配某个位到一个值(例如位 25 = 0xd5) 我该怎么做?
非常简化的示例代码,如果有帮助的话
import ctypes as *
#ctypes array with ~250,000 c_uint32 elements
huge_arr = (c_uint32*250,000)(*range(250,000)) # Fill with dummy data for this example
class Example(Structure):
_pack_ = 1
_fields_ = [
("a", c_uint16),
("b", c_uint16, 14),
("c", c_uint16, 2),
("d", c_uint32, 24),
("e", c_uint32, 8),
("f", c_uint16),
("g", c_uint16)
]
offset = 123456
example_struct = Example.from_buffer(huge_arr, offset)
# Ideally, I'd like to be able to set bits in example_struct. for example, example_struct[2] = 0x2b
我知道可以通过执行 huge_arr[offset+2] = 0x2b 来执行 example_struct[2] = 0x2b,但我的程序比这个示例更复杂,huge_arr 被定义(并保留)在主文件中,而 example_struct 被传输作为不同文件中另一个函数的参数,因此 huge_arr 超出范围。有没有办法改变 exmaple_struct 的第 n 位?
需要注意的另一件事是,该程序是用 Python 2.7 编写的,但即使是 python3 解决方案也将不胜感激
预先感谢您的帮助(我肯定会为任何可以解决此问题的善良的灵魂标记最佳答案)
子衿沉夜
相关分类