【问题标题】:How can I "prepare " char arrays to boost::asio::streambuf::mutable_buffers_type buffers?如何“准备”字符数组来 boost::asio::streambuf::mutable_buffers_type 缓冲区?
【发布时间】:2015-11-22 07:07:31
【问题描述】:

在我的项目中,我将各种文件读入不同的缓冲区,然后想使用 boost::asio::streambuf 将这些缓冲区连接在一起以加快进程。我已阅读 http://www.boost.org/doc/libs/1_59_0/doc/html/boost_asio/reference/streambuf.html 中的示例。

boost::asio::streambuf b;
// reserve 512 bytes in output sequence
boost::asio::streambuf::mutable_buffers_type bufs = b.prepare(512);
size_t n = sock.receive(bufs);
// received data is "committed" from output sequence to input sequence
b.commit(n);
std::istream is(&b);
std::string s;
is >> s;

我的问题是如何在我“准备好”bufs 之后按顺序手动分配多个 char 数组 (char buf[512]) 给 boost::asio::streambuf::mutable_buffers_type bufs? 例如,我想知道是否有办法:

    some_copy_func(bufs, array1,copy_size1); 
    some_copy_func(bufs, array2,copy_size2); 
    some_copy_func(bufs, array3,copy_size3);  

在这些副本之后,array1、array2 和 array3 将按照相同的顺序复制到 bufs。在我打电话之后 b.commit(copy_size1+copy_size2+copy_size1),这些数组中的所有缓冲区都将在b的istream端可用。

我尝试搜索 boost 文档,但找不到任何方法来执行此操作。我知道有 boost::asio::buffer_copy() 允许您将外部缓冲区复制到“bufs”,但是这个 buffer_copy() 会破坏 bufs 的旧数据。 有没有人在这个问题上有类似的经验?谢谢。

【问题讨论】:

    标签: c++ boost


    【解决方案1】:

    ostream

    最简单的方法是按预期使用streambuf...作为streambuf:

    boost::asio::streambuf sb;
    
    {
        char a[512], b[512], c[512];
        std::ostream os(&sb);
        os.write(a, sizeof(a));
        os.write(b, sizeof(b));
        os.write(c, sizeof(c));
    }
    

    copy

    boost::asio::streambuf sb;
    
    {
        boost::asio::streambuf::mutable_buffers_type bufs = sb.prepare(3 * 512);
        auto it = buffers_begin(bufs);
        char a[512], b[512], c[512];
    
        it = std::copy_n(a, sizeof(a), it);
        it = std::copy_n(b, sizeof(b), it);
        it = std::copy_n(c, sizeof(c), it);
    
        sb.commit(sizeof(a) + sizeof(b) + sizeof(c));
    }
    

    【讨论】:

    • 谢谢!这绝对有效。顺便说一句,我认为“std::ostream os(&sb);”可以在第二个 sn-p 中删除
    • 是的。我在复制/粘贴中错过了:)
    猜你喜欢
    • 2016-09-19
    • 2018-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-09
    • 2017-09-02
    • 2023-03-25
    • 2011-08-06
    相关资源
    最近更新 更多