开发者

C/C++ map binary data to struct members [closed]

开发者 https://www.devze.com 2023-02-10 05:33 出处:网络
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical andcannot be reasonably answered in its current form. For help clari
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 12 years ago.

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:

  1. What is the best way to do this?
  2. 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

  1. take into account the length of the datatype.
  2. handle different address models and endianness.
  3. display bo开发者_开发知识库th hex, and a native display for that particular data type.
  4. 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消