如果我使用Boost库序列化类容器的实例:
class Container
{
public:
Block** blocks;
int blocksNumber;
}
class Block
{
public:
int blockType;
unsigned char* data;
}
然后填写所有必要的数据以获得完整的容器:
Container container = new Container();
container.blocksNumber=5;
Block** blocks = (Block**)malloc(sizeof(Block*)*container.blocksNumber);
blocks[0] = (Block*)malloc(sizeof(Block));
//..... Filling all the necessary data... and constructing the container
所以我的问题是:实例容器的序列化格式是否包含所有已分配的数据?换句话说,如果我反序列化容器的序列化格式,我是否能够读取数据的内容?非常感谢你!
答案 0 :(得分:0)
我不会浪费任何时间考虑你为何带来不安全的C型加农炮。您正在寻找使用Boost Serialization,一个现代通用的C ++库。
这是它应该是什么样子:
struct Block {
int blockType;
std::vector<uint8_t> data;
};
struct Container {
std::vector<std::vector<Block>> block_lists;
};
查看完整的工作样本:
<强> Live On Coliru 强>
#include <boost/serialization/vector.hpp>
class Block
{
public:
int blockType;
std::vector<uint8_t> data;
private:
friend class boost::serialization::access;
template <typename Ar> void serialize(Ar& ar, unsigned) {
ar & blockType;
ar & data;
}
};
class Container
{
public:
std::vector<std::vector<Block>> block_lists;
private:
friend class boost::serialization::access;
template <typename Ar> void serialize(Ar& ar, unsigned) {
ar & block_lists;
}
};
#include <boost/archive/text_oarchive.hpp>
int main()
{
Container const letshavesome = {
{ // block_lists
{
Block { 1, { 0x11, 0x12, 0x13, 0x14 } },
Block { 2, { 0x21, 0x22, 0x23, 0x24 } },
Block { 3, { 0x31, 0x32, 0x33, 0x34 } },
},
{
Block { 4, { 0x41, 0x42, 0x43, 0x44 } },
Block { 5, { 0x51, 0x52, 0x53, 0x54 } },
Block { 6, { 0x61, 0x62, 0x63, 0x64 } },
},
}
};
boost::archive::text_oarchive oa(std::cout);
oa << letshavesome;
}
输出
22 serialization::archive 11 0 0 0 0 2 0 0 0 3 0 0 0 1 4 0 17 18 19 20 2 4 0 33 34 35 36 3 4 0 49 50 51 52 3 0 4 4 0 65 66 67 68 5 4 0 81 82 83 84 6 4 0 97 98 99 100