C ++将多个对象序列化为一个文件,并反序列化有限数量的对象

时间:2016-04-22 20:04:40

标签: c++ serialization boost vector boost-serialization

在开始之前,请考虑以下代码:

一个数据传输对象ObjectDTO

class ObjectDTO {

public:
    int id;
    string string1;
    string string2;
    string string3;
    int code1;
    vector<string> stringList1;

private:
    friend class boost::serialization::access;

    template<class Archive>
    void serialize(Archive &archive, const unsigned int version) {
        archive & id;
        archive & string1;
        archive & string2;
        archive & string3;
        archive & code1;
        archive & stringList1;
    }

序列化

void OutputStreamService::writeReportsToFile(vector<ObjectDTO> objects, int filename){
    ofstream outputFileStream(to_string(filename));
    boost::archive::binary_oarchive outputArchive(outputFileStream);
    outputArchive << objects;
}

反序列化

vector<ObjectDTO> InputStreamService::readObjects() {
    ifstream inputFileStream(to_string(fileNumber++));
    boost::archive::binary_iarchive inputArchive(inputFileStream);
    vector<ObjectDTO> objects;
    inputArchive >> objects;
    return objects;
}

我正在使用Boost Serialization C ++库来序列化vector ObjectDTO并稍后再读回来。

Supose i生成了30GB的随机ObjectDTO并将其保存到同一个文件

我怎样才能只阅读其中一些以避免达到内存限制?

我正在使用Boost序列化,因为这是我找到解决第一个问题的简单方法但我可以在必要时更改为任何其他方法!

2 个答案:

答案 0 :(得分:1)

使用Google协议缓冲区,有用于序列化的CodedOutputStream类和用于反序列化的CodedInputStream。

CodedOutputStream方法之一是WriteVarint32,它允许编写一个可以用作流中索引的数字。

在CodeInputStream中有相应的ReadVarint32方法,例如

序列化:

char text[[]] = "Hello world!";
coded_output->WriteVarint32(strlen(text));
coded_output->WriteRaw(text, strlen(text));

反序列化:

uint32 size;
coded_input->ReadVarint32(&size);

char* text = new char[size + 1];
coded_input->ReadRaw(buffer, size);

最后一行允许您从给定索引开始读取序列化流的内容。

以下是我在开始时使用给定长度序列化/反序列化流的两种方法。

template < class T>
void TProtoBufSerializer::SerializeImplementation(const T& protoBuf, std::vector<char>& buffer ) 
{
    int bufLength = protoBuf.ByteSize() + google::protobuf::io::CodedOutputStream::VarintSize32(protoBuf.ByteSize());
    buffer.resize(bufLength);

    google::protobuf::io::ArrayOutputStream arrayOutput(&buffer[0], bufLength);
    google::protobuf::io::CodedOutputStream codedOutput(&arrayOutput);

    codedOutput.WriteVarint32(protoBuf.ByteSize());
    protoBuf.SerializeToCodedStream(&codedOutput);     
}

template < class T>
bool TProtoBufSerializer::DeSerializeImplementation(std::vector<char>& buffer, T& protoBuf )
{
   bool deserialized = false;

   google::protobuf::io::ArrayInputStream arrayInput(&buffer[0],buffer.size());
   google::protobuf::io::CodedInputStream codedInput(&arrayInput);

   unsigned int object_size;
   bool header_readed = codedInput.ReadVarint32(&object_size);

   if(header_readed && object_size > 0)
   {
       if( buffer.size() >= codedInput.CurrentPosition() + object_size )
       {
           google::protobuf::io::CodedInputStream::Limit limit = codedInput.PushLimit(object_size);

           if(protoBuf.ParseFromCodedStream(&codedInput))
           {
               std::vector<char>::iterator it = buffer.begin();
               std::advance(it,codedInput.CurrentPosition());
               std::move(it,buffer.end(),buffer.begin() );
               buffer.resize(buffer.size() - codedInput.CurrentPosition());
               deserialized = true;
           }
           else
           {
              throw TProtoBufSerializerPayloadException();
           }
           codedInput.PopLimit(limit);
       }
   }
   else
   {
       //varint32 which is used in header is at the most 5 bytes long, 
       //if given buffer is 5 bytes or more long and header still cannot be decoded - raise exception 
       if(buffer.size() >= 5) 
       {
          throw TProtoBufSerializerHeaderException();
       }
   }
   return deserialized;
}

答案 1 :(得分:1)

我解决了丢弃Boost序列化和向量的问题,分别在writeread上使用普通的旧C ++ ofstreamifstream

我的OutputStreamService writeObjectsToFile结束如下:

void OutputStreamService::writeObjectssToFile(ObjectDTO * objects, int filename){
        ofstream outputFileStream(to_string(filename), std::ios::binary);
        outputFileStream.write((char *)&objects, sizeof(objects));
}

带有readObjects的InputStreamService:

ObjectDTO * InputStreamService::readObjects() {
    ifstream inputFileStream(to_string(fileNumber++), std::ios::binary);
    ObjectDTO objects[10];
    inputFileStream.read((char *)&objects, sizeof(objects));
    return objects;
}

这样我可以将10或任何其他整数定义为我想要读入的对象数。

为了解决mais问题,我现在可以计算出我的内存可以处理的对象的aprox数量,然后限制读取次数!

泰!