C++ boost::asio::带有向量结构的缓冲区

C++ boost::asio::带有向量结构的缓冲区,c++,boost-asio,C++,Boost Asio,我有两个问题: 在我的信息结构中,如果我有float或double类型而不是std::string,它工作得很好,但是如果我像下面那样使用std::string,在我的客户端部分,我会收到结构,但在那之后它就崩溃了 我甚至不能用std::vector发送它,就像这样: 结构信息 { int-id; std::字符串名; }; int main(int argc,字符**argv) { boost::asio::io_服务ios; boost::asio::ip::tcp::endpoint e

我有两个问题:

  • 在我的信息结构中,如果我有
    float
    double
    类型而不是
    std::string
    ,它工作得很好,但是如果我像下面那样使用
    std::string
    ,在我的客户端部分,我会收到结构,但在那之后它就崩溃了

  • 我甚至不能用std::vector发送它,就像这样:


  • 结构信息 { int-id; std::字符串名; }; int main(int argc,字符**argv) { boost::asio::io_服务ios; boost::asio::ip::tcp::endpoint ep(boost::asio::ip::address::from_string(“127.0.0.1”),12345); boost::asio::ip::tcp::socketcl1(ios); cl1.open(ep.protocol()); boost::system::error_code ec; cl1.连接(ep、ec); 如果(ec==0) 库特
  • 在我的信息结构中,如果我有
    float
    double
    类型而不是
    std::string
    ,它工作得很好,但是如果我像下面那样使用
    std::string
    ,在我的客户端部分,我会收到结构,但在那之后它就崩溃了
  • 这是因为
    float
    double
    是POD数据类型,而
    std::string
    不是,违反了合同:

    boost::asio::buffer
    函数用于创建缓冲区对象,以表示原始内存、POD元素数组、POD元素向量或
    std::string

    准确地说,它们的意思是“[POD元素的数组|向量]或[a
    std::string
    ]”,当您查看

    添加一个静态断言,您将看到:

    static_assert(std::is_pod<info>::value, "whoops, that can't work");
    cl1.send(boost::asio::buffer(&student, sizeof(student)));
    
    static_assert(std::is_pod::value,“哎哟,那不行”);
    发送(boost::asio::buffer(&student,sizeof(student));
    
    如果您想序列化它,您必须编写一些代码。假设架构独立性和可移植性通常不是问题,则可以:

    int32_t id_and_size[] = {student.id, static_cast<int32_t>(student.name.length())};
    assert(id_and_size[1] >= 0); // because `size_t` is unsigned and larger than int32_t
    
    cl1.send(boost::asio::buffer(id_and_size));
    cl1.send(boost::asio::buffer(student.name.data(), student.name.length()));
    
    int32_t id_和_size[]={student.id,static_cast(student.name.length())};
    assert(id_和_size[1]>=0);//因为'size_t'是无符号的,并且大于int32\u t
    发送(boost::asio::buffer(id_和_大小));
    send(boost::asio::buffer(student.name.data(),student.name.length());
    
    这将发送与数据分开的长度:在Coliru上直播]()

    00000000:0700 0000 0500 0000 5261 7375 6c…….拉苏尔

    虽然这是容易出错和繁琐的。如果你控制两端,考虑一个序列化框架(Boost序列化,谷歌原型Buff.…)


    既然您已经提到了序列化原始二进制形式的
    double
    等2->“info st1;st1.id=0;st1.name=“abd”;vector st;st.push_back(st1);cl1.send(boost::asio::buffer(&st,sizeof(st));-->在客户端“read”方法中发送,但不接收如果我使用std::array,它可以工作,但与std::vector的工作方式不同,请帮助我,我哪里做错了???提前感谢欢迎来到StackOverflow。请阅读并解决您问题中的问题。要获得更多帮助,请查看和其他部分。
    int32_t id_and_size[] = {student.id, static_cast<int32_t>(student.name.length())};
    assert(id_and_size[1] >= 0); // because `size_t` is unsigned and larger than int32_t
    
    cl1.send(boost::asio::buffer(id_and_size));
    cl1.send(boost::asio::buffer(student.name.data(), student.name.length()));