C/C++ map binary data to struct members [closed]
Lets say, I have the following text file:
Listing 1:
Endianess=little
AddressModel=32
typedef struct{
int x;
int y;
float f;
double d;
} A;
instance1:0x0000000100000002000048C19A99999999993C40
instance2:0x00100257000000090000000FBA99359976992397
Where instance1 corresponds to an instance of struct A, such as:
Listing 2:
A->x = 0x00000001 = 1
A->y = 0x00000002 = 2
A->f = 0x000048C1 = -12.5
A->d = 0x9A99999999993C40 = 28.6
The Task:
Write an application that takes as a text file, an arbitrary C data structure, and an arbitrary memory dump, and print out in an easy-to-read format, a reconstruction of the instance of that struct (such as what is seen in Listing 2).
The Questions:
- What is the best way to do this?
- Rather than re-invent the wheel, is(are) there any Open-source solutions that this problem might benefit from?
Things to consider:
The solution will have to
- take into account the length of the datatype.
- handle different address models and endianness.
- display bo开发者_开发知识库th hex, and a native display for that particular data type.
- take C structs that were NOT linked into the program you are writing.
Bonus Question:
Handle a case with embedded structs:
typedef struct{
int q;
int p;
A a; //embedded struct of type A defined in listing 1
} B;
Thanks in advance everyone!
You cannot use reflection in C or C++ so that's out. That means you will need to write a parser than can read C struct definitions. Not hard at all really.
You can do it yourself if you want: tokenizing and parsing C is not hard. Or you could use tools like lex and yacc. Or you could use a C++ library like Boost Spirit.
Once you've got a parser then you can build the data reader in C. You don't want to reproduce the struct in your C code. You just want to be able to read it properly.
I would write an array of data types and names during the parse step. During the binary read step, step through the array and read however many bytes you need to read, then produce the output line. Repeat until you run out of data types in the array.
精彩评论