c++中編碼protobuf repeated string


參考:http://www.cppblog.com/API/archive/2014/12/09/209070.aspx

proto文件

addressbook.proto

syntax = "proto3";
package lm; 
message group_s 
{ 
   string             group_name = 1;
   repeated string    member_name = 2;
}

C++程序

  • 編碼proto文件
    probufwriter.cpp
#include "addressbook.pb.h"
#include <fstream>
#include <iostream>
using namespace std;

int main(void) 
{ 
    lm::group_s msg1; 
    msg1.set_group_name("Class-1"); 
    for(int j =0; j<3; j++){ 
        std::string m_name = "student_"+to_string(j);
        msg1.add_member_name(m_name);
        cout << msg1.member_name(j) << endl;               //打印出string數組元素
    }
    // Write the new address book back to disk. 
    fstream output("./log", ios::out | ios::trunc | ios::binary); 
            
    if (!msg1.SerializeToOstream(&output)) { 
        cerr << "Failed to write msg." << endl; 
        return -1; 
    }         
    return 0; 
}
  • 解碼proto文件
    probufread.cpp
#include "addressbook.pb.h"
#include <iostream>
#include <fstream>
using namespace std;


void ListMsg(const lm::group_s & msg) { 
    for(int j =0; j<3; j++){ 
        cout << msg.member_name(j) << endl; 
    }
    cout << msg.group_name() << endl; 
} 
  
int main(int argc, char* argv[])
{ 
 
    lm::group_s msg1; 

    { 
        fstream input("./log", ios::in | ios::binary); 
        if (!msg1.ParseFromIstream(&input)) { 
        cerr << "Failed to parse address book." << endl; 
        return -1; 
        } 
    } 

    ListMsg(msg1); 

}

編譯運行

編譯環境

安裝好protobuf庫
安裝方法:https://www.cnblogs.com/abc36725612/p/14196674.html

編譯

參考:https://www.cnblogs.com/huanyinglvtuan/p/14119328.html

  • 生成c++結構體
# protoc -I=. --cpp_out=. ./addressbook.proto
# ls
README.md  addressbook.pb.cc  addressbook.pb.h  addressbook.proto  probufread.cpp  probufwriter.cpp

編譯c++程序

# g++ -std=c++11 -g -Wall addressbook.pb.cc probufwriter.cpp -o s -lprotobuf -I /include -lpthread
# g++ -std=c++11 -g -Wall addressbook.pb.cc probufread.cpp -o c -lprotobuf -I /include -lpthread
運行
# ./s
student_0
student_1
student_2
# ./c
student_0
student_1
student_2
Class-1


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM