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.
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.
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";
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