Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ stream to memory

Tags:

c++

stream

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.

like image 237
Budric Avatar asked Apr 24 '09 16:04

Budric


2 Answers

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.

like image 125
Judge Maygarden Avatar answered Sep 22 '22 09:09

Judge Maygarden


#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 
like image 29
Joachim Avatar answered Sep 18 '22 09:09

Joachim