reading struct in python from created struct in c

后端 未结 4 1092
广开言路
广开言路 2020-12-01 12:48

I am very new at using Python and very rusty with C, so I apologize in advance for how dumb and/or lost I sound.

I have function in C that creates a .dat file contai

4条回答
  •  春和景丽
    2020-12-01 13:25

    I had same problem recently, so I had made module for the task, stored here: http://pastebin.com/XJyZMyHX

    example code:

    MY_STRUCT="""typedef struct __attribute__ ((__packed__)){
        uint8_t u8;
        uint16_t u16;
        uint32_t u32;
        uint64_t u64;
        int8_t i8;
        int16_t i16;
        int32_t i32;
        int64_t i64;
        long long int lli;
        float flt;
        double dbl;
        char string[12];
        uint64_t array[5];
    } debugInfo;"""
    
    PACKED_STRUCT='\x01\x00\x01\x00\x00\x01\x00\x00\x00\x00\x00\x01\x00\x00\x00\xff\x00\xff\x00\x00\xff\xff\x00\x00\x00\x00\xff\xff\xff\xff*\x00\x00\x00\x00\x00\x00\x00ff\x06@\x14\xaeG\xe1z\x14\x08@testString\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00\x04\x00\x00\x00\x00\x00\x00\x00\x05\x00\x00\x00\x00\x00\x00\x00'
    
    if __name__ == '__main__':
        print "String:"
        print depack_bytearray_to_str(PACKED_STRUCT,MY_STRUCT,"<" )
        print "Bytes in Stuct:"+str(structSize(MY_STRUCT))
        nt=depack_bytearray_to_namedtuple(PACKED_STRUCT,MY_STRUCT,"<" )
        print "Named tuple nt:"
        print nt
        print "nt.string="+nt.string
    

    The result should be:

    String:
    u8:1
    u16:256
    u32:65536
    u64:4294967296
    i8:-1
    i16:-256
    i32:-65536
    i64:-4294967296
    lli:42
    flt:2.09999990463
    dbl:3.01
    string:u'testString\x00\x00'
    array:(1, 2, 3, 4, 5)
    
    Bytes in Stuct:102
    Named tuple nt:
    CStruct(u8=1, u16=256, u32=65536, u64=4294967296L, i8=-1, i16=-256, i32=-65536, i64=-4294967296L, lli=42, flt=2.0999999046325684, dbl=3.01, string="u'testString\\x00\\x00'", array=(1, 2, 3, 4, 5))
    nt.string=u'testString\x00\x00'
    

提交回复
热议问题