简体   繁体   English

C++ stream 至 memory

[英]C++ stream to memory

how can I create std::ostream and std::istream objects to point to a piece of memory I allocated and manage (I don't want the stream to free my memory).我如何创建std::ostreamstd::istream对象以指向我分配和管理的一块 memory(我不希望 stream 释放我的内存)。

I was looking at using rdbuf()->pubsetbuf() to modify one of the other streams - say sstringstream .我正在考虑使用rdbuf()->pubsetbuf()来修改其他流之一 - 比如sstringstream However I think streambuf used by stringstream will free the buffer afterwards?但是我认为stringstream使用的 streambuf 之后会释放缓冲区吗?

Basically I'm trying to serialize some things to shared memory.基本上我正在尝试将一些东西序列化为共享 memory。

Thanks.谢谢。

Take a look at the bufferstream class in theBoost.Interprocess library:看一下Boost.Interprocess库中的bufferstream类:

The bufferstream classes offer iostream interface with direct formatting in a fixed size memory buffer with protection against buffer overflows. bufferstream 类提供 iostream 接口,在固定大小的内存缓冲区中直接格式化并防止缓冲区溢出。

#include <iostream>
#include <streambuf>

//...
size_t length = 100;
auto pBuf = new char[length]; // allocate memory

struct membuf: std::streambuf // derive because std::streambuf constructor is protected
{
   membuf(char* p, size_t size) 
   {
       setp( p, p + size); // set start end end pointers
   }
   size_t written() {return pptr()-pbase();} // how many bytes were really written?
};

membuf sbuf( pBuf, length ); // our buffer object
std::ostream out( &sbuf );   // stream using our buffer

out << 12345.654e10 << std::endl;
out.flush();

std::cout << "Nr of written bytes: " << sbuf.written() << std::endl;
std::cout << "Content: " << (char*)pBuf << std::endl;

//...
delete [] pBuf; // free memory 

A minimal memory buffer has to implemented only the overflow function of std::streambuf and keep track of the get pointers of the streambuf .最小的 memory 缓冲区必须仅实现std::streambufoverflow function 并跟踪 streambuf 的获取指针 This is done viasetp and pbump .这是通过setppbump完成的。

You will also need to add an underlying memory buffer, but this can be done rather easy.您还需要添加一个底层 memory 缓冲区,但这可以很容易地完成。 cppreference.com has a good example of an implementation based on an std::array in the already mentioned page for the overflow function. While this is a good start to learn, you might want to have a memory buffer that can resize. cppreference.com 在已经提到的overflow页面 function 中有一个基于std::array的实现的很好示例。虽然这是一个很好的学习开始,但您可能想要一个可以调整大小的 memory 缓冲区。 You can try to implement it based on an std::vector (like I did here ).您可以尝试基于std::vector实现它(就像我在这里所做的那样)。

I ended up writing a memory buffer based on std::realloc to get the most performance while also giving me the possibility to hand the raw pointer over to C libaries.我最终基于std::realloc编写了一个 memory 缓冲区以获得最佳性能,同时也让我有可能将原始指针移交给 C 库。 You can find my implementation here .你可以在这里找到我的实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM