ブーストを使用してc++オブジェクトをファイルにシリアル化するのは本当に簡単です。
std::ofstream ofile( lpszFileName );
boost::archive::text_oarchive oa(ofile);
oa << m_rgPoints;
しかし、どうすればc ++オブジェクトを生のメモリブロックにシリアル化できますか?
出力ファイルストリームをメモリに読み込む必要がありますか、それとも他のより良い方法がありますか?
ありがとう。
ブーストを使用してc++オブジェクトをファイルにシリアル化するのは本当に簡単です。
std::ofstream ofile( lpszFileName );
boost::archive::text_oarchive oa(ofile);
oa << m_rgPoints;
しかし、どうすればc ++オブジェクトを生のメモリブロックにシリアル化できますか?
出力ファイルストリームをメモリに読み込む必要がありますか、それとも他のより良い方法がありますか?
ありがとう。
James Kanzeからのコメントに応えて編集:
あなたは:にシリアル化することができstd::ostringstream
ます
std::ostringstream oss;
boost::archive::text_oarchive oa(oss);
oa << m_rgPoints;
次に、std::streambuf
(呼び出しoss.rdbuf()
)を取得し、それを呼び出しstreambuf::sgetn
てデータを独自のバッファーに読み込むことにより、そこから読み取ります。
http://www.cplusplus.com/reference/iostream/ostringstream/rdbuf/
これにより、不要な一時ファイルを回避できます。
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";
実際には、バイナリ生データのシリアル化ラッパーがあります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::vector
ですstd::byte
。のリファレンスでreinterpret_cast
詳しく説明されているように、ポインタをaにキャストし、それをbyte *
逆参照することができます。したがって、次のようなコードを使用できます。
// 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;
ただし、これはコピーを意味します。
私が理解しているなら、バイナリシリアル化が必要ですboost::archive::binary_oarchive
。次に、ストリームからデータをコピーできます。