[英]How to use python ctypes with a bytearray?
如何使用 python 的ctypes
库从字节ctypes
中读/写?
我可以创建如下结构:
from ctypes import *
class Foo(Structure):
_fields_ = [
('b0', c_byte),
('b1', c_byte),
('s0', c_short),
('l0', c_long),
]
f = Foo(1, 0x42, 0xF00F, 0x12345678)
但是dir(Foo)
没有显示任何从字节数组创建 Foo 的方法,并且dir(f)
没有显示任何将 Foo 转换为字节数组或写入字节数组的方法。 我错过了什么吗?
假设我们有以下类型
from ctypes import *
class Foo(Structure):
_fields_ = [
('b0', c_byte),
('b1', c_byte),
('s0', c_short),
('l0', c_long),
]
f = Foo(1, 0x42, 0xF00F, 0x12345678)
您只需使用bytearray
即可将值作为字节获取:
f_bytearray = bytearray(f)
同样,如果你想改变一个字节数组,你可以这样做:
b = bytearray(32)
b[10:10+sizeof(f)] = f
如果要将 bytearray 转换为结构,可以使用from_buffer
注意:由于某些原因,在 python3 中,
from_buffer
不包含在dir(Foo)
。
# shares the buffer: mutating f will mutate f_bytearray
f = Foo.from_buffer(f_bytearray)
# OR copies the data to a new buffer
f = Foo.from_buffer_copy(f_bytearray)
奖励:您可以从(例如) Foo.l0.offset
获取偏移信息。 有了这个,你应该能够读/写一个结构到字节数组没问题:D
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.