1

我有一个 google protobuf 序列化字符串(它是一个序列化字符串),它包含文本、mac 地址和 ip 地址(以字节为单位)。我正在尝试使用 python c 类型用这个字符串制作 ac 结构。如果我的 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 数组中没有连续的零,这将完美地工作。

4

1 回答 1

0

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')
于 2018-03-03T11:53:58.793 回答