gpt4 book ai didi

在 C 预处理器中创建结构

转载 作者:太空宇宙 更新时间:2023-11-04 03:18:28 26 4
gpt4 key购买 nike

现在,我正在用 C 编写一个小项目来测试一些序列化技术。我这样做的一种方法是使用 union 。我想尝试的是在 C 预处理器中创建一个包含用户定义结构的 union 。例如,像这样:

#define create_union(name_of_structure, type_of_structure) \ 
\
typedef union name_of_structure { \
typeof(type_of_structure) structure; \
char buffer_that_holds_structure[sizeof(type_of_structure)]; \
} name_of_structure;

/* Usage */
struct my_data {
int id;
int other_value;
};

create_union(my_data_t, struct my_data);
/* Data type my_data_t (union my_data_t) now exists */

首先,这个可行吗?如果是这样,我将如何去做呢?如果没有,我可以使用其他方法吗?

谢谢!

最佳答案

是的,这是可能的,而且您的代码非常接近正确。

我会在宏定义的末尾去掉分号。我也会放弃使用 typeof;它不可移植,也不需要它,除非您想使用表达式而不是类型名称作为 create_union 的第一个参数。

我可能会这样定义它。 (我不为结构或 union 类型打扰 typedef;我只使用名称 struct foounion foo 除非该类型旨在完全不透明。随意如果您愿意,可以使用 typedef。)(我还使用了 unsigned char 而不是 char,因为这是定义对象表示的方式。)

#define CREATE_UNION(new_type, existing_type) \
union new_type { \
existing_type obj; \
unsigned char rep[sizeof(existing_type)]; \
}

然后你可以这样做:

CREATE_UNION(int_wrapper, int);
int_wrapper foo;

请注意,您定义的是 union ,而不是结构

关于在 C 预处理器中创建结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49019113/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com