#include <iostream>
#include <google/protobuf/compiler/importer.h>
#include <google/protobuf/dynamic_message.h>
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;
MyErrorCollector errorCollector;
sourceTree.MapPath("","/usr/local/include/");//test.proto中有可能引用其他庫
sourceTree.MapPath("","./");
google::protobuf::compiler::Importer importer(&sourceTree, &errorCollector);
importer.Import("test.proto");
auto descriptor1 = importer.pool()->FindMessageTypeByName("T.Test");
if(descriptor1 == nullptr)
{
std::cout << "descriptor1 is null" << std::endl;
return 0;
}
google::protobuf::DynamicMessageFactory factory;
auto proto1 = factory.GetPrototype(descriptor1);
auto message1= proto1->New();
auto reflection1 = message1->GetReflection();
auto filed1 = descriptor1->FindFieldByName("id");
reflection1->SetInt32(message1,filed1,1);
std::cout << message1->DebugString();
auto filed2 = descriptor1->FindFieldByName("name");
reflection1->SetString(message1,filed2,"adfafafdafaf");
std::cout << message1->DebugString();
delete message1 ;
return 0 ;
}
//g++ -g -std=c++0x -o a.out reflect.cpp -lpthread -lprotobuf
/*
syntax = "proto2";
package T;
message Test
{
optional int32 id = 1;
}
*/
protobuf反射
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.