簡體   English   中英

協議緩沖區問題,多個序列化成二進制文件

[英]Protocol buffers issue, multiple serializations into a binary file

我從protobuf二進制文件io得到了一些奇怪的行為。 我正在將文本語料庫預處理為protobuf中間文件。 我的序列化類看起來如下:

  class pb_session_printer
  {
  public:
    pb_session_printer(std::string & filename)
      : out(filename.c_str(), std::fstream::out | std::fstream::trunc | 
                              std::fstream|binary)
      {}

    void print_batch(std::vector<session> & pb_sv)
    {
      boost::lock_guard<boost::mutex> lock(m);

      BOOST_FOREACH(session & s, pb_sv)
      {
        std::cout << out.tellg() << ":";
        s.SerializeToOstream(&out);
        out.flush();
        std::cout << s.session_id() << ":" << s.action_size() << std::endl;
      }
      exit(0);
    }

    std::fstream out;
    boost::mutex m;
  };

一段輸出看起來像:

0:0:8
132:1:8
227:2:6
303:3:6
381:4:19
849:5:9
1028:6:2
1048:7:18
1333:8:28
2473:9:24

第一個字段顯示序列化正常進行。

當我運行我的加載程序時:

int main()
{
  std::fstream in_file("out_file", std::fstream::in | std::ios::binary);
  session s;

  std::cout << in_file.tellg() << std::endl;
  s.ParseFromIstream(&in_file);
  std::cout << in_file.tellg() << std::endl;
  std::cout << s.session_id() << std::endl;

  s.ParseFromIstream(&in_file);
}

我明白了:

0
-1
111
libprotobuf ERROR google/protobuf/message_lite.cc:123] Can't parse message of type 
"session" because it is missing required fields: session_id

session_id:111是流的末尾的一個條目,我顯然不理解庫的binary-io設施的語義。 請幫忙。

如果在單個文件中編寫多個protobuffers,則需要編寫protobuf + protobuffer的大小並單獨讀取它們(因此沒有像Cat Plus Plus中提到的ParseFromIstream )。 當您在protobuffer中讀取時,可以使用ParseFromArray對其進行ParseFromArray

您的文件看起來大小(這些空間僅用於提高可讀性):

大小protobuf大小protobuf大小protobuf等

Message::ParseFromIstream 被記錄為使用整個輸入。 由於您正在序列化相同類型的消息序列,因此您可以使用該類型的repeated字段創建新消息,並使用該消息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM