【问题标题】:How to print to screen a struct and all its content?如何打印以筛选结构及其所有内容?
【发布时间】:2013-01-28 21:58:40
【问题描述】:

我想在c/c++ 中找到一个宏,它获取结构typedef 和一个指向结构的指针作为输入并打印其所有内容:

假设我有一个名为 struct account 的结构。

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

我是这样使用的:

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

我想要一个在 linux kernel/c 语言中看起来像这样的宏:

PRINT_STRUCT_CONTENT(struct_type, pointer)

并打印以下内容:

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

这个想法是在内核中有一种dir python 函数


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

【问题讨论】:

标签: c++ c debugging linux-kernel printk


【解决方案1】:

您可以使用print_hex_dumpprint_hex_dump_bytes
示例:

struct mystruct *p;
print_hex_dump_bytes("mystruct: ", DUMP_PREFIX_ADDRESS, p, sizeof(*p));

【讨论】:

  • -1 因为可移植性问题。这是一种最好手动实现的东西,而不是引入在许多系统上无法满足的外部依赖项。编辑:重新阅读问题并删除-1。
  • 您所要求的似乎无法在 C 中以通用方式实现。您需要为每种类型的结构生成代码,也许编写一个解析源文件并生成每个结构的打印功能。然后,如果您有 struct somestruct *a 使用 somestruct_print(a) 或将结构定义包装在一个宏中,该宏还定义了该结构的打印函数。出于调试目的,十六进制转储应该足够 IMO,因为它包含您需要的所有信息,而不是您想要的“漂亮”。
【解决方案2】:

您可能想看看kernel trace event API。它比简单的printk 稍微复杂一些,但它是动态可切换的并且可以进行一些漂亮的(-ier)打印。而且开销仍然很低。

【讨论】:

  • @0x90:我链接的 LWN.net 文章是三篇系列文章之一。这是一个很好的分步参考。
猜你喜欢
  • 2015-05-23
  • 2023-03-09
  • 1970-01-01
  • 1970-01-01
  • 2013-03-20
  • 2018-11-25
  • 1970-01-01
  • 1970-01-01
  • 2019-07-30
相关资源
最近更新 更多