typedef struct {
union {
char a[8];
struct {
unsigned long z;
unsigned long o;
} ss;
} ss;
} st3;
我在内存中有这个结构 我想将它序列化为我可以使用的结构,如何正确序列化它? 谢谢。
最佳答案
作为 n.m.在他的评论中的言论,你必须知道 union 包含什么。为此,通常定义结构如下:
typedef struct {
int union_type;
union {
char a[8];
struct {
unsigned long z;
unsigned long o;
} ss;
} ss;
} st3;
其中 union_type
表示 union 是否包含 char 数组或结构。如果你知道这一点,你可以序列化结构并且接收者可以重新构造它,因为在序列化 union 之前,你输出 union_type
,然后输出正在使用的成员(字符或结构)。
还有一种选择:确定并集的最大组成部分(此处不相关)并将其输出为二进制字节,例如作为 \x1a\x1b...
的列表。那么你不需要知道 union 里有什么。如果接收器像那样重新组装它,它会将一个完美传输的对象传递给功能程序,让我们希望知道 union 包含什么......注意:此方法要求两台机器的字节顺序相同,否则多头将被错误地重新组装。
关于c - 序列化其中包含 union 和结构的结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31773232/