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).
I was looking at using rdbuf()->pubsetbuf()
to modify one of the other streams - say sstringstream
. However I think streambuf used by stringstream
will free the buffer afterwards?
Basically I'm trying to serialize some things to shared memory.
Thanks.
Take a look at the bufferstream class in the Boost.Interprocess library:
The bufferstream classes offer iostream interface with direct formatting in a fixed size memory buffer with protection against buffer overflows.
#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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With