我想将一个由ctypes中Structure创建的结构体转为python中的bytes,在网上我找到了三种方法,示例如下:
from ctypes import (
BigEndianStructure,
c_uint16,
sizeof,
addressof,
byref,
memmove,
string_at,
create_string_buffer
)
class Flags(BigEndianStructure):
_fields_ = [
("QR", c_uint16, 1), # 查询应答标志
("Opcode", c_uint16, 4), # 查询应答类型
("AA", c_uint16, 1), # 权威回答
("TC", c_uint16, 1), # 截断
("RD", c_uint16, 1), # 递归查询标志
("RA", c_uint16, 1), # 可递归
("Z", c_uint16, 3), # 保留字段
("RCode", c_uint16, 4) # 返回码
]
flags = Flags(1, 1, 0, 1, 1, 1, 1, 1)
# 对应二进制
# 0b 1 0001 0 1 1 1 001 0001 --> 0b10001011 10010001
size = sizeof(Flags)
# 方法一
ptr1 = addressof(flags)
s1 = string_at(ptr1, size)
b1 = int(s1[0])
b2 = int(s1[1])
print(s1)
print(bin(b1), bin(b2))
# 方法二
ptr2 = byref(flags)
s2 = string_at(ptr2, size)
print(s2)
# 方法三
buffer = create_string_buffer(size)
memmove(buffer, ptr2, size)
s3 = buffer.raw
# 或者
# s3 = bytes(buffer)
print(s3)
运行结果:
b'\x8b\x91'
0b10001011 0b10010001
b'\x8b\x91'
b'\x8b\x91'
与预期的结果一样,但是这三种方法有什么区别?或者说这种写法有没有问题?