将包含位字段和动态数据的结构复制到 Char 数组缓冲区中

Copying struct with bitfields & dynamic data into a Char array buffer

本文关键字:复制 Char 数组 缓冲区 结构 字段 包含位 动态 数据      更新时间:2023-10-16

我具有以下

的结构
struct Struct {
    int length; //dynamicTest length 
    unsigned int b: 1;
    unsigned int a: 1;
    unsigned int padding: 10;
    int* dynamicTest;
    int flag; 
}

我想将其复制到char阵列缓冲区(以发送插座)。我很好奇我会怎么做。

确切地说,您可以使用 memcpy,例如:

#include <string.h>
/* ... */
Struct s = /*... */;
char buf[1024]
memcpy(buf, &s, sizeof(s));
/* now [buf, buf + sizeof(s)) holds the needed data */

另外,您可以完全避免复制 view struct作为char数组的实例(由于计算机内存中的所有内容都是字节的顺序,因此此方法有效)。

Struct s = /* ... */;
const char* buf = (char*)(&s);
/* now [buf, buf + sizeof(s)) holds the needed data */

如果要通过网络发送它,则需要照顾字节订单,INT大小和许多其他详细信息。

复制位字段没有任何问题,但是对于动态字段(例如您的char*),这种天真的方法无法使用。与其他任何类型一起使用的更通用的解决方案是序列化。