1

I would like to find a macro in c/c++ which gets struct typedef and a pointer to a struct as inputs and prints all its content like that:

let say I have a struct named struct account.

struct account {
   int account_number;
   char *first_name;
   char *last_name;
   float balance;
};

and I use it this way:

struct account my_account= {    
    .account_number = 321321,
    .first_name = 0x12345678,
    .last_name = 0,
    .balance = 222 };

I want a macro in linux kernel/ c lanaguge that look like that:

PRINT_STRUCT_CONTENT(struct_type, pointer)

and printk the following:

my_account= {
account_number = 321321,
first_name = 0x12345678,
last_name = 0,
balance = 222
}

the idea is to have kind of dir python function in the kernel


Write a Macro to stringify the contents of a struct

Your most general C macro for printing variable values in different types

Is there a C preprocessor macro to print out a struct?

Writing a while loop in the C preprocessor

Community
  • 1
  • 1
0x90
  • 39,472
  • 36
  • 165
  • 245
  • I can't tell what you're asking. Do you want this functionality in the kernel or in Python? – Michael Jan 28 '13 at 22:51
  • edited the question. see also this: http://answers.yahoo.com/question/index?qid=20081120161132AAnv8o1 – 0x90 Jan 31 '13 at 11:03

2 Answers2

3

You can use print_hex_dump or print_hex_dump_bytes
Example:

struct mystruct *p;
print_hex_dump_bytes("mystruct: ", DUMP_PREFIX_ADDRESS, p, sizeof(*p));
0x90
  • 39,472
  • 36
  • 165
  • 245
bahaa
  • 199
  • 4
  • -1 because of portability issues. this is the kind of thing that is better implemented by hand instead of pulling in external dependencies that can't be satisfied on many systems. EDIT: reread the question and removed the -1. – Andreas Grapentin Jan 31 '13 at 11:05
  • What you're asking for doesn't seem possible to implement in a generic way in C. You need to generate code for each type of struct, maybe write a a tool that parses source files and generates a print function for each struct. then if you have struct somestruct *a use somestruct_print(a) or wrap struct definitions in a macro which also defines a print function for that struct. for debugging purposes a hex dump should be enough IMO as it contains all the information you need, just not as "pretty" as you'd like. – bahaa Jan 31 '13 at 12:33
1

You might want to take a look at the kernel trace event API. It's slightly more complex than a simple printk, but it's dynamically switchable and does some prett(-ier) printing. And still very low-overhead.

sheu
  • 5,653
  • 17
  • 32
  • 1
    @0x90: the LWN.net article I linked is one of a series of three. It's a good step-by-step reference. – sheu Jan 31 '13 at 11:22