c++ boost::asio::buffer 和结构
无论如何,基本上可以执行以下操作:
#include <boost/asio.hpp>
struct testStruct{
int x;
int y;
};
int main(){
struct testStruct t;
boost::asio::buffer b;
b = boost::asio::buffer(t);
return 0;
}
似乎失败的地方是将“t”传递到缓冲区“b”。
Is there anyway to BASICALLY do the following:
#include <boost/asio.hpp>
struct testStruct{
int x;
int y;
};
int main(){
struct testStruct t;
boost::asio::buffer b;
b = boost::asio::buffer(t);
return 0;
}
Where it seems to fail is passing 't' into the buffer, 'b'.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用分散操作多个缓冲区:
请注意,您需要在接收端使用相应的收集。除了您提出的人为示例之外,这会变得非常乏味。这就是为什么我建议在您的 < href="https://stackoverflow.com/questions/5599302/boostasio-async-write-complex-struct">上一个问题。
Use the scatter operation of more than a single buffer:
Note you'll need to use a corresponding gather on the receiving side. This gets very tedious with anything more than the contrived example you have presented. Which is why I suggested using a more robust serialization mechanism in your previous question.
只需使用 Boost.Serialization
您可以从 http://www.boost_asio/examples.html 获取演示。 boost.org/doc/libs/1_47_0/doc/html/boost_asio/examples.html
当你想发送一个对象时,最好先序列化它。
Just Use Boost.Serialization
You can get a demo from the http://www.boost.org/doc/libs/1_47_0/doc/html/boost_asio/examples.html
When you want to send an Object, It is better for you to Serialize it First.
有几件事你需要小心。
1.填充
结构的布局是特定于实现的。服务器上结构体的 x 和 y 成员之间完全有可能存在占位符字节,而客户端上则没有。
要解决此问题,您应该将结构成员逐个序列化到字符缓冲区中,并以相同的方式在客户端上反序列化它们。
您可以编写一些实用程序代码来帮助您解决此问题,这是一个起点:
2。字节顺序
根据体系结构,或者在某些情况下甚至取决于当前的 CPU 模式(某些 POWER CPU 支持字节顺序切换),成员的字节可能会颠倒。您必须检测主机体系结构的字节顺序,并将字节交换为预定义的顺序以在您的协议中使用。
There are a few things you need to be careful of.
1. Padding
The layout of your struct is implementation-specific. It's entirely possible for there to be placeholder bytes between the x and y members of your struct on the server, and none on the client.
To work around this, you should serialize your structures member by member into a character buffer, and deserialize them on the client in the same manner.
You could write some utility code to help you with this, here's a starting point:
2. Endianness
Depending on architecture, or in some cases even depending on the current CPU mode (some POWER CPUs support endianness switching), the bytes of your members may be reversed. You have to detect the endianness of the host architecture, and swap the bytes to a predefined order for use in your protocol.