Python ctypesgen/ctypes: How to write struct fields to file in single byte alignment

后端 未结 1 1734
青春惊慌失措
青春惊慌失措 2021-01-20 05:04

Using ctypesgen, I generated a struct (let\'s call it mystruct) with fields defined like so:

[(\'somelong\', ctypes.c_long),
 (\'somebyte\', ctypes.c_ubyte)
         


        
相关标签:
1条回答
  • 2021-01-20 05:05

    Define _pack_=1 before defining _fields_.

    Example:

    from ctypes import *
    from io import BytesIO
    from binascii import hexlify
    
    def dump(o):
        s=BytesIO()
        s.write(o)
        s.seek(0)
        return hexlify(s.read())
    
    class Test(Structure):
        _fields_ = [
            ('long',c_long),
            ('byte',c_ubyte),
            ('long2',c_long),
            ('str',c_char*5)]
    
    class Test2(Structure):
        _pack_ = 1
        _fields_ = [
            ('long',c_long),
            ('byte',c_ubyte),
            ('long2',c_long),
            ('str',c_char*5)]
    
    print dump(Test(1,2,3,'12345'))
    print dump(Test2(1,2,3,'12345'))
    

    Output:

    0100000002000000030000003132333435000000
    0100000002030000003132333435
    

    Alternatively, use the struct module. Note it is important to define the endianness < which outputs the equivalent of _pack_=1. Without it, it will use default packing.

    import struct
    print hexlify(struct.pack('<LBL5s',1,2,3,'12345'))
    

    Output:

    0100000002030000003132333435
    
    0 讨论(0)
提交回复
热议问题