c ++ boost将char数组反序列化为obj
Posted
技术标签:
【中文标题】c ++ boost将char数组反序列化为obj【英文标题】:c++ boost deserialize char array into an obj 【发布时间】:2018-04-04 16:56:56 【问题描述】:在 boost 公交时刻表示例代码中。bus schedule sample 我尝试反序列化 char 数组中的数据。所以我添加了这个功能。但它有这个错误。怎么了?
void frombuffer_schedule(char* buffer,const bus_schedule& obj)
boost::iostreams::stream<boost::iostreams::array_source> is(buffer, 4096);
boost::archive::binary_iarchive ia(is,boost::archive::archive_flags::no_header);
ia >> obj;
错误是“错误:静态断言失败:typex::value”
【问题讨论】:
你使用的是什么版本的 boost?该静态断言位于哪个文件和行号? 【参考方案1】:您正在反序列化为 const
对象。以下是该失败断言的实际代码:
// cannot load data into a "const" object unless it's a
// wrapper around some other non-const object.
BOOST_STATIC_ASSERT(typex::value);
所以,修复它:)
Live On Coliru
#include <boost/serialization/string.hpp>
#include <boost/serialization/serialization.hpp>
struct MyData
std::string s;
float values[7];
private:
friend class boost::serialization::access;
template <typename Ar>
void serialize(Ar& ar, unsigned) ar & s & values;
;
#include <boost/iostreams/device/array.hpp>
#include <boost/iostreams/device/back_inserter.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/archive/binary_oarchive.hpp>
#include <boost/archive/binary_iarchive.hpp>
namespace bio = boost::iostreams;
std::vector<char> to_buffer(const MyData& obj)
std::vector<char> buffer;
bio::stream<bio::back_insert_device<std::vector<char> > > os(buffer);
namespace ba = boost::archive;
ba::binary_oarchive oa(os, ba::archive_flags::no_header);
oa << obj;
return buffer;
void from_buffer(char* buffer, MyData& obj)
bio::stream<bio::array_source> is(buffer, 4096);
namespace ba = boost::archive;
ba::binary_iarchive ia(is, ba::archive_flags::no_header);
ia >> obj;
#include <iostream>
#include <iomanip>
static inline std::ostream& operator<<(std::ostream& os, MyData const& object)
os << "s:" << std::quoted(object.s) << ", values:[";
for (float v : object.values)
os << " " << v;
return os << " ]";
int main()
auto buffer = to_buffer(MyData "hello world", 1,2,3,4,5,6,7 );
MyData received;
from_buffer(buffer.data(), received);
std::cout << "Received: " << received << "\n";
打印
Received: s:"hello world", values:[ 1 2 3 4 5 6 7 ]
【讨论】:
以上是关于c ++ boost将char数组反序列化为obj的主要内容,如果未能解决你的问题,请参考以下文章