程式語言 - GNU - C/C++ - Protocol Buffers



參考資訊:
https://github.com/afiskon/cpp-protobuf-example/tree/master
https://stackoverflow.com/questions/47704968/protoc-command-not-found-linux
https://stackoverflow.com/questions/62707863/how-to-encode-messages-with-map-using-google-protobuf-in-javascript-protocol

main.proto

syntax = "proto3";
 
package mytest.Test;
 
message Who {
    string name = 1;
    int64 value = 2;
    map<string, string> items = 3;
}

main.cpp

#include <iostream>
#include <fstream>
#include <stdexcept>
#include "main.pb.h"
 
using namespace std;
using namespace mytest::Test;
 
int main(int argc, char **argv)
{
    GOOGLE_PROTOBUF_VERIFY_VERSION;
 
    Who t1;
    t1.set_name("t1");
    t1.set_value(100);
    (*t1.mutable_items())["1"] = "egg";
    (*t1.mutable_items())["2"] = "apple";
 
    fstream out("t1.dat", ios::out | ios::trunc | ios::binary);
    t1.SerializeToOstream(&out);
    out.close();
 
    Who t2;
    fstream in("t1.dat", ios::in | ios::binary);
    t2.ParseFromIstream(&in);
    in.close();
 
    cout << "t2.name: " << t2.name() << endl;
    cout << "t2.value: " << t2.value() << endl;
    cout << "t2.items_size: " << t2.mutable_items()->size() << endl;

    google::protobuf::Map t2_items = *t2.mutable_items();
    for (google::protobuf::Map<string, string>::const_iterator it = t2_items.begin(); it != t2_items.end(); it++) {
        cout << "[" << it->first << "] = " << it->second << endl;
    }
 
    return 0;
}

編譯、執行

$ protoc --cpp_out . main.proto
$ g++ main.cpp -o test main.pb.cc -I. -lprotobuf
$ ./test
    t2.name: t1
    t2.value: 100
    t2.items_size: 2
    [2] = apple
    [1] = egg