如何序列化为原始内存块?

Jic*_*hao 4 c++ serialization boost

使用boost将c ++对象序列化为文件非常容易,

std::ofstream ofile( lpszFileName );
boost::archive::text_oarchive oa(ofile);
oa << m_rgPoints;
Run Code Online (Sandbox Code Playgroud)

但是,如何将c ++对象序列化为原始内存块?

我应该将输出文件流读入内存还是有其他更好的方法?

谢谢.

Ale*_*son 5

编辑回应James Kanze的评论:

您可以序列化为std::ostringstream:

std::ostringstream oss;
boost::archive::text_oarchive oa(oss);
oa << m_rgPoints;
Run Code Online (Sandbox Code Playgroud)

然后通过获取std::streambuf(调用oss.rdbuf())并调用streambuf::sgetn它来读取数据到您自己的缓冲区中.

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

这可以避免不必要的临时文件.


Nas*_*zta 5

您可以编写自己的streambuf类,直接在您的内存上运行:

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;
  }
};
Run Code Online (Sandbox Code Playgroud)

使用此类:

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

  oss << "Write to the buffer";
Run Code Online (Sandbox Code Playgroud)