直接将序列化提升为char数组

sco*_*man 21 c++ serialization boost

Boost序列化文档断言,序列化/反序列化项目的方法是使用二进制/文本存档以及基础结构上的流.如果我不想将序列化数据用作std :: string,这可以正常工作,但我的目的是将其直接转换为char*缓冲区.如何在不创建临时字符串的情况下实现此目的?

解决了!对于想要一个例子的人:

char buffer[4096];

boost::iostreams::basic_array_sink<char> sr(buffer, buffer_size);  
boost::iostreams::stream< boost::iostreams::basic_array_sink<char> > source(sr);

boost::archive::binary_oarchive oa(source);

oa << serializable_object; 
Run Code Online (Sandbox Code Playgroud)

mar*_*nus 34

如果您事先不知道要发送的数据的大小,这是序列化为以下内容的通用方法std::string:

// serialize obj into an std::string
std::string serial_str;
boost::iostreams::back_insert_device<std::string> inserter(serial_str);
boost::iostreams::stream<boost::iostreams::back_insert_device<std::string> > s(inserter);
boost::archive::binary_oarchive oa(s);

oa << obj;

// don't forget to flush the stream to finish writing into the buffer
s.flush();

// now you get to const char* with serial_str.data() or serial_str.c_str()
Run Code Online (Sandbox Code Playgroud)

要反序列化,请使用

// wrap buffer inside a stream and deserialize serial_str into obj
boost::iostreams::basic_array_source<char> device(serial_str.data(), serial_str.size());
boost::iostreams::stream<boost::iostreams::basic_array_source<char> > s(device);
boost::archive::binary_iarchive ia(s);
ia >> obj;
Run Code Online (Sandbox Code Playgroud)

这就像一个魅力,我使用它来发送MPI数据.

如果您保留serial_str在内存中,这可以非常快速地完成,并且serial_str.clear()在序列化之前只需调用它.这会清除数据但不释放任何内存,因此当您的下一个序列化数据大小不需要时,不会进行分配.

  • 不,std :: string不是以null结尾,所以size()按预期工作. (5认同)

Éri*_*ant 6

IIUC,你想写一个固定大小的预分配数组.

你可以使用boost :: iostreams :: array_sink(用stream包装,为它提供一个std :: ostream接口).