[英]insert a struct into a vector as binary data for network transmission
我正在为旧产品使用较旧的网络传输功能,该功能需要一个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
开头的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());
它具有以下优点:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.