简体   繁体   English

如何从 ctypes.Structure 取回原始缓冲区?

[英]How do I get back original buffer from a ctypes.Structure?

msg is created using extra bytes ie more than sizeof(Message) msg是使用额外的字节创建的,即超过sizeof(Message)

from ctypes import *

class Message(Structure):
    _fields_ = [("length",  c_ushort),
                ("version", c_ubyte),
                ("type",    c_ubyte),
                ("index",   c_int),
                ("flags",   c_int),
    ]

msg = Message.from_buffer(bytearray.fromhex('1000 05 06 01000000 deadbeef cccccccc'))

But, bytes(msg) just returns sizeof(Message) bytes.但是, bytes(msg)只返回sizeof(Message)字节。

>>> bytes(msg).hex()
'1000050601000000deadbeef'

How do I retrieve the original bytearray from msg ?如何从msg检索原始字节数组? Do I need to make a more elaborate Message class that overrides __bytes__ , from_buffer etc.?我是否需要制作更详尽的Message class 来覆盖__bytes__from_buffer等?

It looks like "Message" is a header and the total size in length is the header size plus the variable data after the header. Define the header, then make a factory function that dynamically creates a structure with a header and an array of the appropriate size:看起来“消息”是一个 header,总length是 header 大小加上 header 之后的变量数据。定义 header,然后创建一个工厂 function,它动态地创建一个具有适当数组的结构 8818530080658尺寸:

from ctypes import *

class Header(Structure):
    _fields_ = [("length", c_ushort),
                ("version", c_ubyte),
                ("type", c_ubyte),
                ("index", c_int),
                ("flags", c_int)]

def make_msg(hexstring):

    buf = bytearray.fromhex(hexstring)
    datalen = len(buf) - sizeof(Header)

    class Message(Structure):
        _fields_ = [("header", Header),
                    ("data", c_char * datalen)]

    return Message.from_buffer(buf)

msg = make_msg('1000 05 06 01000000 deadbeef cccccccc')
print(msg.header.length)
print(msg.data)

Output: Output:

16
b'\xcc\xcc\xcc\xcc'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM