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
posted @ 2020-12-26 10:21  liqinglucky  阅读(1962)  评论(0编辑  收藏  举报