How to serialize into a raw memory block?

boost, c++, serialization

Solution

You could write own `streambuf` class, what works directly on your memory:

class membuf : public std::streambuf
{
public:
  membuf( char * mem, size_t size )
  {
    this->setp( mem, mem + size );
    this->setg( mem, 0, mem + size );
  }
  int_type overflow( int_type charval = traits_type::eof() )
  {
    return traits_type::eof();
  }
  int_type underflow( void )
  {
    return traits_type::eof();
  }
  int sync( void )
  {
    return 0;
  }
};

Use this class:

  membuf buf(address,size);
  ostream os(&buf);
  istream is(&buf);

  oss << "Write to the buffer";

Problem

It is really easy to serialize a c++ object to file with boost, ``` std::ofstream ofile( lpszFileName ); boost::archive::text_oarchive oa(ofile); oa << m_rgPoints; ``` But how could I serialize a c++ object into a raw memory block? Should I read the output file stream into memory or is there any other better method? Thanks.

Original source