在矢量中插入一个结构作为网络传输的二进制数据
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
开头的指针作为迭代器),并依赖于这样一个事实,即这里的结构将至少与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());
这具有以下优点:
- 永远不能过大或过小
- 自动存储持续时间和堆栈分配意味着这可能会更快
相关文章:
- 在本地网络中通过OpenCV(C++)实时流式传输图像
- 用于本地网络运行的客户端服务器体系结构
- 将数据从阵列火阵列传输到犰狳结构
- 分段错误:C++中的结构序列化和 MPI 数据传输
- 使用 UDP 协议从 Windows 套接字发送到 Qt 套接字的网络数据包上的结构编码和解码
- ESP8266网络服务器如何流式传输未签名的字符
- ffmpeg H264一次对帧进行编码,用于网络流传输
- 网络传输时间从TCP/IP堆栈
- 在网络上传输数据
- 通过网络中的套接字进行文件传输时,该程序中的文件传输错误是什么
- 定义网络通信的结构
- 通过网络发送 Python c_types结构
- 如何使用套接字构建健壮的网络体系结构
- 用于使用 istream/ostream 传输消息的类似网络协议
- C++/CLI(.NET)等效于将结构写入网络的本机C++
- C++ 序列化 std::error_code 以便通过网络传输或保存到磁盘
- 使用C++测量网络上 2 个应用程序之间的数据传输速率(带宽),如何获得公正准确的结果
- 消息队列用c++用Qt进行网络传输
- 通过网络传输int
- 在矢量中插入一个结构作为网络传输的二进制数据