Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serialize into a raw memory block?

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.

like image 371
Jichao Avatar asked Jun 20 '12 07:06

Jichao


2 Answers

Edited in response to comments from James Kanze:

You could serialize into a std::ostringstream:

std::ostringstream oss;
boost::archive::text_oarchive oa(oss);
oa << m_rgPoints;

And then read from that by getting the std::streambuf (calling oss.rdbuf()) and calling streambuf::sgetn on that to read the data into your own buffer.

http://www.cplusplus.com/reference/iostream/ostringstream/rdbuf/

This avoids an unnecessary temporary file.

like image 166
Alex Wilson Avatar answered Oct 11 '22 14:10

Alex Wilson


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";
like image 41
Naszta Avatar answered Oct 11 '22 12:10

Naszta