5

使用 boost 将 c++ 对象序列化到文件中真的很容易,

std::ofstream ofile( lpszFileName );
boost::archive::text_oarchive oa(ofile);
oa << m_rgPoints;

但是我怎么能将一个 c++ 对象序列化为一个原始内存块呢?

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

谢谢。

4

4 回答 4

7

针对 James Kanze 的评论进行了编辑:

您可以序列化为std::ostringstream

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

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

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

这避免了不必要的临时文件。

于 2012-06-20T08:03:21.763 回答
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;
  }
};

使用这个类:

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

  oss << "Write to the buffer";
于 2012-06-20T08:16:38.230 回答
0

实际上有一个二进制原始数据的序列化包装器,binary_object.

你可以像这样使用它:

// buf is a pointer to a raw block of memory, size its size
// oa is a boost archive
boost::serialization::binary_object buf_wrap(buf, size);
oa << buf_wrap

使用 c++17 的另一种选择是将缓冲区转换std::vectorstd::byte. 如参考中reinterpret_cast所述,允许将指针强制转换为 abyte *并取消引用它。因此,可以使用如下代码:

// buf is a pointer to a raw block of memory, size its size
// oa is a boost archive
auto start_buf = reinterpret_cast<byte *>(buf);
std::vector<std::byte> vec(start_buf, start_buf + size);
oa << vec;

然而,这意味着副本。

于 2020-04-28T04:31:13.330 回答
-1

如果我了解您需要二进制序列化boost::archive::binary_oarchive。然后您可以从流中复制数据。

于 2012-06-20T07:52:13.280 回答