简体   繁体   English

将结构作为二进制数据插入向量中以进行网络传输

[英]insert a struct into a vector as binary data for network transmission

I am using an older network transmission function for a legacy product, which takes a char array and transmits it over the network. 我正在为旧产品使用较旧的网络传输功能,该功能需要一个char数组并通过网络进行传输。 This char array is just data, no need for it make sense (or be null terminated). 这个char数组只是数据,不需要它(或以null终止)。 As such in the past the following occurred: 过去,发生了以下情况:

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.

We have just added a bunch of stuff to robot_info but i am not happy with the single length method of the above code, i would prefer a dynamiclly allocated raii type in order to be expandable, especially since there can be multiple robot_info structures. 我们刚刚在robot_info添加了很多东西,但是我对上述代码的单长度方法不满意,我更喜欢动态分配的raii类型以使其可扩展,特别是因为可以有多个robot_info结构。 I propose the following: 我提出以下建议:

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());

Live example. 现场示例。

Using the std::vector insert function (with a pointer to the start of r_info as the iterator) and relying on the fact that a struct here would be aligned to at least a char and can be operated on like this. 使用std::vector insert函数(使用指向r_info开头的r_info作为迭代器),并依赖于以下事实:此处的结构至少要与char对齐,并且可以像这样操作。 The struct has no dynamic memory elements, and no inheritance. 该结构没有动态内存元素,也没有继承。

Will this have well defined behavior? 这会有明确的行为吗? Is there a better way to perform the same action? 有没有更好的方法来执行相同的操作?

While this works, it is ultimately solving a compile time problem with a run time solution. 在此可行的同时,它最终将通过运行时解决方案解决编译时问题。 Since robot_info is a defined type, a better solution would be this: 由于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());

This has the advantages: 它具有以下优点:

  1. Can never be over size, or undersized 绝对不能过大或过小
  2. Automatic Storage duration and stack allocation means this is potentially faster 自动存储持续时间和堆栈分配意味着这可能更快

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

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