How to print to screen a struct and all its content?

6.4k Views Asked by At

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

2

There are 2 best solutions below

2
On

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));
1
On

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.