如何在C中转储任意结构? [英] How do I dump an arbitrary struct in C?
问题描述
我不知道要去哪个方向,也许像反射之类的东西会有所帮助?
I don't know which direction to go,perhaps something like reflection will help?
推荐答案
如果您使用的是使用Clang 8或更高版本,您现在可以使用内置的编译器函数 __ builtin_dump_struct
来转储结构。它使用编译时自然可用的信息来生成漂亮地打印结构的代码。
If you're using Clang 8 or newer, you can now use the built-in compiler function __builtin_dump_struct
to dump a struct. It uses the information that's naturally available at compile time to generate code that pretty-prints a struct.
示例代码演示了该函数:
Example code demonstrating the function:
dumpstruct.c:
#include <stdio.h>
struct nested {
int aa;
};
struct dumpme {
int a;
int b;
struct nested n;
};
int main(void) {
struct nested n;
n.aa = 12;
struct dumpme d;
d.a = 1;
d.b = 2;
d.n = n;
__builtin_dump_struct(&d, &printf);
return 0;
}
示例编译运行:
$ clang dumpstruct.c -o dumpstruct
$ ./dumpstruct
struct dumpme {
int a : 1
int b : 2
struct nested n : struct nested {
int aa : 12
}
}
如果您未使用Clang> = 8,但您正在使用GCC,则切换起来非常容易。只需安装clang-8或clang-9软件包,并将 gcc
的调用替换为 clang
。
If you're not using Clang >= 8 but you are using GCC, it's pretty easy to switch. Just install the clang-8 or clang-9 package and replace invocations of gcc
with clang
.
这篇关于如何在C中转储任意结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!