简体   繁体   English

将具有位域和动态数据的结构复制到Char数组缓冲区中

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

I have a struct like the following 我有一个像下面的结构

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

I want to copy this into a char array buffer (to send over a socket). 我想将此复制到char数组缓冲区(以通过套接字发送)。 I'm curious how I would do that. 我很好奇我会怎么做。

To be precise, you do this with memcpy , eg: 确切地说,您可以使用memcpy进行此操作,例如:

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

Alternatively you can avoid copying at all and view an instance of struct as an array of char (since everything in computer memory is sequence of bytes, this approach works). 或者,也可以在所有避免复制和查看结构的实例为char(因为一切在计算机存储器是一个字节序列,这种方法的工作原理)的阵列。

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

If you are going to send it over the network, you need to care of byte order, int size and many other details. 如果要通过网络发送,则需要注意字节顺序,整数大小和许多其他详细信息。

Copying bit fields present no problem, but for dynamic fields, such as your char* this naive approach won't work. 复制位字段没有问题,但是对于动态字段(例如char*这种幼稚的方法将行不通。 The more general solution, that works with any other types is serialization . 与任何其他类型一起使用的更通用的解决方案是序列化

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM