boost asio write/read vector(boost asio 写/读向量)
问题描述
我无法从 boost asio 缓冲区读取向量.我有这个向量:
I have trouble reading a vector from boost asio buffer. I have this vector:
std::vector<float> points;
我用 boost asio write 发送
And I send it with boost asio write
boost::asio::write (socket, boost::asio::buffer(&new_buffers->points.front(), nr_points * 3 * sizeof (float)));
另一方面,我有:
std::vector<float> recv_vector;
tcp_socket.async_read_some(boost::asio::buffer(recv_vector), read_handler);
当我执行 recv_vector.size() 时,它总是空的.
When I do recv_vector.size(), its always empty.
谁能告诉我我做错了什么?
Can somebody tell me what I am doing wrong?
马雷克
推荐答案
Asio 不是序列化库.它不会序列化随机向量(你可以使用 Boost Serialization).
Asio is not a serialization library. It does not serialize random vectors (you could use Boost Serialization for that).
它只是将您的缓冲区视为 IO 操作的数据缓冲区.所以,例如在第二种情况下:
It merely treats your buffer as the data buffer for the IO operation. So, e.g. in the second instance:
std::vector<float> recv_vector;
tcp_socket.async_read_some(boost::asio::buffer(recv_vector), read_handler);
您告诉它接收适合由向量 recv_vector 表示的 POD 缓冲区的数据量,该向量为空.因此,您是在告诉 Asio 接收 0 字节,我认为它会为您带来快乐.
you tell it to receive the amount of data that fits into the POD buffer represented by the vector recv_vector, which is empty. You are therefore telling Asio to receive 0 bytes, which I presume it will do happily for you.
要解决问题,请使用序列化(将责任交给另一个库)或在实际数据之前手动发送向量的大小.
To fix things, either use serialization (putting the responsibility in the hands of another library) or manually send the size of the vector before the actual data.
我在这里有更多解释和完整示例:如何从套接字读取中接收自定义数据类型?
I have more explanations and a full sample here: How to receive a custom data type from socket read?
还要注意,您不必做那么复杂的事情:
Note, as well, that you don't have to do that complicated thing:
boost::asio::write (socket, boost::asio::buffer(&new_buffers->points.front(), nr_points * 3 * sizeof (float)));
相反,对于 POD 类型向量,只需 让 Asio 进行计算和转换:
Instead, for POD type vectors, just let Asio do the calculations and casts:
boost::asio::write (socket, buffer(new_buffers->points));
这篇关于boost asio 写/读向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:boost asio 写/读向量
基础教程推荐
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- CString 到 char* 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
