How to use Python to map bytes to C struct?

Viewed 152

I have a nested C struct (size is very large) and bytes

// In C:
struct example1 {
  int val1;
  int val2;
  int val3;
  int val4; 
  char c1;
  char c2;
  enum example2 e1;
  union example3 u1;
  struct example4 s1;
  ...
  ....
  ....
};
# In python
example1_bytes = b'\x08\x09\x0a\x0b...........'

How to map the bytes to C struct and access the member?

1 Answers

If you need to map those bytes in python, you can use struct.unpack()

The official Python Documentation will tell you how to write the format argument to map C types.

Example:

import struct
mapped_bytes = struct.unpack(">ii", example_bytes)
Related