Question

I have lots of c-structs (containing substructs containing unions containing substructs...)) and would like to print them in a similar way like gcc can do.

So I dont want to do things like described in How do I dump an arbitrary struct in C?, coz thats just a hexdump

and I also dont want to invent some kind of introspection (java/modern c++ like), but just want to use the knowledge gcc has/generates for gdb, and add some knowledge I have (like how to select the right variant of a union)

like proposed in Linux C: Easy & 'pretty' dump/printout of structs (like in gdb) - from source code?.

So my plan is: Take all that nice c-code I have, let gcc work on it and produce some meta-info, which in a second turn gets parsed/analyzed by something, which then is able to interpret/print a piece of memory according to that information.

There is a utility in Linux called pstruct/c2ph, whicht does something similar and seems to be at some level of knowledge which could be modified to do what I want..

So, basically Im looking for a tool which takes a file containing

struct X {
   int a;
   char *b;
 }

and produces a function lile printX (void *p); which then prints something like {a:1, b:"lala"}, if p points to the according X

So is there something out there which can already do that? I have the feeling that pstruct is very close...

Was it helpful?

Solution

The best and most precise approach is to rely on compiler plugin interface, like those provided by clang and gcc. Basically, the compiler will call callbacks supplied by your plugin on each interesting event (such as encountering declarations), giving you the chance to produce the necessary wrappers/metadata.

Alternative approaches include tools like gcc-xml (which will produce an xml representation of your program), swig and whatever tools capable of parsing DWARF debugging output (that's what gdb uses).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top