python ctypes pragma pack for byte aligned read

前端 未结 1 522
死守一世寂寞
死守一世寂寞 2020-12-17 21:10

I have a C++ application with below structure written to file. Now I need to unmarshal them using python, The basic problem here is how to reflect the pragma pack

相关标签:
1条回答
  • 2020-12-17 21:16

    You can change the packing in ctypes as described here

    By default, Structure and Union fields are aligned in the same way the C compiler does it. It is possible to override this behavior be specifying a pack class attribute in the subclass definition. This must be set to a positive integer and specifies the maximum alignment for the fields. This is what #pragma pack(n) also does in MSVC.

    For your example this would be:

    from ctypes import *
    
    class abc(Structure):
        _pack_ = 1
        _fields_ = [
            ('r1',c_ubyte),
            ('r2',c_ubyte),
            ('p1',c_ubyte),
            ('id',c_uint)]
    
    0 讨论(0)
提交回复
热议问题