Packing struct in Boost Asio buffer

前端 未结 3 1449
悲&欢浪女
悲&欢浪女 2021-01-18 21:18

I\'m looking for a way to send a packet made of a custom data structure through a socket with Boost Asio. At the moment I understand that you can send a string with the stan

3条回答
  •  没有蜡笔的小新
    2021-01-18 21:57

    You can just copy POD objects bitwise.

    In fact, Asio accepts boost/std array, T[] or vector buffers as long as T is a POD struct.

    • http://www.boost.org/doc/libs/1_55_0/doc/html/boost_asio/overview/core/buffers.html
    • http://www.boost.org/doc/libs/1_55_0/doc/html/boost_asio/reference/buffer.html for the various constructors for mutable/const buffer sequence wrappers.

    Otherwise, you could use Boost Serialization to serialize your data.

    Finally, there's some support for binaries (binary dwords (big-endian/little-endian), binary floats) in Boost Spirit.

    Update Example:

    #include 
    #include 
    
    int main()
    {
        struct { float a, b; } arr[10];
    
        auto mutable_buffer = boost::asio::buffer(arr);
    }
    

    See it Live On Coliru

提交回复
热议问题