我有一个google protobuf序列化字符串(它是一个序列化的字符串),它包含文本,mac地址和ip地址(以字节为单位)。我正在尝试使用python c类型使用此字符串创建一个c结构。如果我的mac或ip包含连续的零,它将破坏要在结构中打包的字符串。 bytesarray将填充0。
from ctypes import *
def create_structure(serialized_string):
msg_length = len(serialized_string)
print(serialized_string)
class CommonMessage(Structure):
_pack_ = 1
_fields_ = [("sof", c_uint), ("request_id", c_uint), ("interface", c_uint), ("msg_type", c_uint),
("response", c_uint), ("data_len", c_int), ("data", c_char * msg_length)]
sof = 4293844428
common_msg = CommonMessage(sof, 123456,
11122946,
6000, 0, msg_length,
serialized_string
)
print(bytearray(common_msg))
breaking_string = b'\n&\n\x0f000000000000000\x12\x05durga\x1a\x06\xab\xcd\xef\x00\x00\x00"\x04\x00\x00!\x04\x12\x12000000001111000000\x1a$1c715f33-79dc-4244-9afc-b1669f3cfac2'
create_structure(breaking_string)
如果char数组中没有连续的零,这将完美地工作。
ctypes
有一些“有用”的转换,在这种情况下无济于事。如果对阵列使用c_ubyte
类型,则不会使用转换。它不会接受字节字符串作为初始化程序,但您可以构造一个c_ubyte
数组:
from ctypes import *
def create_structure(serialized_string):
msg_length = len(serialized_string)
print(serialized_string)
class CommonMessage(Structure):
_pack_ = 1
_fields_ = [("sof", c_uint), ("request_id", c_uint), ("interface", c_uint), ("msg_type", c_uint),
("response", c_uint), ("data_len", c_int), ("data", c_ubyte * msg_length)]
sof = 4293844428
common_msg = CommonMessage(sof, 123456,
11122946,
6000, 0, msg_length,
(c_ubyte*msg_length)(*serialized_string)
)
print(bytearray(common_msg))
breaking_string = b'\n&\n\x0f000000000000000\x12\x05durga\x1a\x06\xab\xcd\xef\x00\x00\x00"\x04\x00\x00!\x04\x12\x12000000001111000000\x1a$1c715f33-79dc-4244-9afc-b1669f3cfac2'
create_structure(breaking_string)
输出:
b'\n&\n\x0f000000000000000\x12\x05durga\x1a\x06\xab\xcd\xef\x00\x00\x00"\x04\x00\x00!\x04\x12\x12000000001111000000\x1a$1c715f33-79dc-4244-9afc-b1669f3cfac2'
bytearray(b'\xcc\xdd\xee\xff@\xe2\x01\x00\x02\xb9\xa9\x00p\x17\x00\x00\x00\x00\x00\x00b\x00\x00\x00\n&\n\x0f000000000000000\x12\x05durga\x1a\x06\xab\xcd\xef\x00\x00\x00"\x04\x00\x00!\x04\x12\x12000000001111000000\x1a$1c715f33-79dc-4244-9afc-b1669f3cfac2')