7

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.

ilya1725
  • 3,936
  • 7
  • 37
  • 59
Budric
  • 3,461
  • 8
  • 34
  • 38

2 Answers2

10

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.

Judge Maygarden
  • 26,095
  • 9
  • 78
  • 98
1
#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 
ilya1725
  • 3,936
  • 7
  • 37
  • 59
Joachim
  • 771
  • 7
  • 11