protobuf descriptor

  1. cpp中如何使用pb.h :protobuf入門教程(六):導入定義(import)
  2. protoc編譯找不到library或者 linker failed, 直接binary重新編一把 https://blog.csdn.net/Programmer_H/article/details/8890800

test.cpp

#include <google/protobuf/compiler/importer.h>
#include <google/protobuf/dynamic_message.h>

#include <iostream>
#include <string>
using namespace std;
class MyErrorCollector
   : public google::protobuf::compiler::MultiFileErrorCollector {
 virtual void AddError(const std::string& filename, int line, int column,
                       const std::string& message) {
   // define import error collector
   printf("%s, %d, %d, %s\n", filename.c_str(), line, column, message.c_str());
 }
};

int main() {
 google::protobuf::compiler::DiskSourceTree sourceTree;  // source tree
 sourceTree.MapPath("", "./");
 MyErrorCollector errorCollector;
 google::protobuf::compiler::Importer importer(&sourceTree, &errorCollector);
 const google::protobuf::FileDescriptor* filedes =
     importer.Import("test.proto");
// cout<< "file des = "<<filedes->DebugString()<<endl;
 cout<<"dependecies count = "<<filedes->dependency_count()<<endl;
 const google::protobuf::Descriptor* descriptor =
     importer.pool()->FindMessageTypeByName("lm.helloworld");
 if (!descriptor) {
   perror("Message is not found!");
   exit(-1);
 }

 cout << descriptor->DebugString();

 // create a dynamic message factory
 google::protobuf::DynamicMessageFactory* factory =
     new google::protobuf::DynamicMessageFactory(importer.pool());
 // create a const message ptr by factory method and message descriptor
 const google::protobuf::Message* tmp = factory->GetPrototype(descriptor);

 // create a non-const message object by const message ptr
 // define import error collector
 google::protobuf::Message* msg = tmp->New();

 return 0;
}

test.proto


// test.proto

syntax = "proto3";

package lm;

message helloworld

{

  int32 id = 1;

  string name = 2;

  repeated string hero = 3;
}

編譯命令clang++ test.cpppkg-config --libs --cflags protobuf`

目錄結構:
在這裏插入圖片描述

`

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章