Search code examples
pythonstructmarshalling

Python struct.unpack format from header .h file


I have a header (.h) file describing some datastructures (the data is collected from a sensor). Example:

...
struct SensorIf
{
    DWORD       SensorType;                     
    char        Name[StrSize];    
    DWORD       SerialNumber;     
    ...
};
...

I also have measurements stored as binary files, containing something like this:

0\x00\x00\x00\x00\x00\x00\x00\x00\x00\x...

As far as I understand, binary data can be parsed using the header file. Can I do that in python? If no, what is the easiest way to do it? I figured out that probably unpack function from struct package is what I need, but how do I create a format string from header (.h) file?


Solution

  • The thing is to use ctypes bult-in library. One has to manually specify all the structures and unions in ctypes subclasses and than parse the file with something like:

    from ctypes import Structure, c_uint
    
    class MyStructure(Structure):
       _fields_ = [
            ("field1", c_uint)
        ]
    
    
    with open('binaryfile', 'rb') as f:
        data = MyStructure()
        f.readinto(data)
        print(data.field1)