在矢量中插入一个结构作为网络传输的二进制数据

insert a struct into a vector as binary data for network transmission

本文关键字:结构 网络传输 数据 二进制 一个 插入      更新时间:2023-10-16

我为遗留产品使用了一个较旧的网络传输功能,该功能采用char阵列并通过网络进行传输。这个char数组只是数据,不需要它有意义(或者以null结尾)。因此,在过去发生了以下情况:

struct robot_info {
    int robot_number;
    int robot_type;
    ...
} // A robot info data structure for sending info.

char str[1024], *currentStrPos = str;
robot_info r_info; 
... // str has some header data added to it.
... // robot info structure is filled out
memcpy(currentStrPos, (char *)&r_info, sizeof robot_info); // Add the robot info
scanSocket.writeTo(str, currentStrPos - str); // Write to the socket.

我们刚刚在robot_info中添加了一些内容,但我对上面代码的单长度方法不满意,我更喜欢动态分配的raii类型,以便进行扩展,特别是因为可以有多个robot_info结构。我建议如下:

std::vector<char> str;
... // str has some header information added to it.
... // r_info is filled out.
str.insert(str.end(), (char *)&r_info, (char *)&r_info + sizeof r_info); 
scanSocket.writeTo(str.data(), str.size());

活生生的例子。

使用std::vector insert函数(以指向r_info开头的指针作为迭代器),并依赖于这样一个事实,即这里的结构将至少与char对齐,并且可以这样操作。该结构没有动态内存元素,也没有继承。

这会有明确的行为吗?有没有更好的方法来执行相同的操作

虽然这很有效,但它最终是通过运行时解决方案解决编译时问题。由于robot_info是一种已定义的类型,因此更好的解决方案是:

std::array<char, sizeof robot_info> str;
memcpy(str.data(), static_cast<char *>(&r_info), sizeof robot_info);
scanSocket.writeTo(str.data(), str.size());

这具有以下优点:

  1. 永远不能过大或过小
  2. 自动存储持续时间和堆栈分配意味着这可能会更快