1

I'm working on a python library to parse some logs that are coming back off of a connected device. There are already a huge amount of c header files that include the structure of the logs. I want to be able to pull in the header files directly and access the members of the structures.

We are currently in the stage where new fields are being added to the structures all the time. Really want to enable the FW developers to change the structure and my scripts to continue working. Looking to have the python code and c code leverage the same .h file to avoid changes in one affecting the other.

Any recommendations?

An example log file

//log_header.h

typedef struct log_1
{
  uint16_t log_id;
  uint16_t log_version;
  uint16_t data1;
  uint16_t data2;
} log_element;

And the python I'm hoping I can write

#parse.py

a = log_element(data_read_from_serial)
print(a.data2)
1

You should use ctypes for this. It is part of the standard python library. In an answer to a question on SO I've given an example of how to create ctypes structs. Here's another example for writing to a binary log file:

https://gist.github.com/lonetwin/2bfdd41da41dae326afb

Your structure would look something like:

class LogElement(Structure):
    __fields__ = [
        (log_id, c_uint16),
        (log_version, c_uint16),
        ...
        ...
    ]

Then you should be able to read bytearrays from the log and initialize the structure. Hope this help. Wish you the best.

  • Welcome aboard ! This looks like a great answer (and could be very useful to me ;-) I wish that I could upvote it more (but can't), and look forward to your future contributions ot the site – Mawg Apr 26 at 6:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.