main-desc.cxx 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. #include <fstream>
  2. #include <google/protobuf/descriptor.h>
  3. #include <google/protobuf/descriptor.pb.h>
  4. #include <google/protobuf/dynamic_message.h>
  5. #include <google/protobuf/text_format.h>
  6. #include <iostream>
  7. #include <string>
  8. int main(int argc, char* argv[])
  9. {
  10. std::ifstream fs;
  11. fs.open(argv[1], std::ifstream::in);
  12. google::protobuf::FileDescriptorSet file_descriptor_set;
  13. file_descriptor_set.ParseFromIstream(&fs);
  14. const google::protobuf::DescriptorPool* compiled_pool =
  15. google::protobuf::DescriptorPool::generated_pool();
  16. if (compiled_pool == NULL) {
  17. std::cerr << "compiled pool is NULL." << std::endl;
  18. return 1;
  19. }
  20. google::protobuf::DescriptorPool pool(compiled_pool);
  21. google::protobuf::DynamicMessageFactory dynamic_message_factory(&pool);
  22. for (const google::protobuf::FileDescriptorProto& file_descriptor_proto :
  23. file_descriptor_set.file()) {
  24. const google::protobuf::FileDescriptor* file_descriptor =
  25. pool.BuildFile(file_descriptor_proto);
  26. if (file_descriptor == NULL) {
  27. continue;
  28. }
  29. const google::protobuf::Descriptor* descriptor =
  30. pool.FindMessageTypeByName("example.msgs.ExampleDesc");
  31. if (descriptor == NULL) {
  32. continue;
  33. }
  34. google::protobuf::Message* msg =
  35. dynamic_message_factory.GetPrototype(descriptor)->New();
  36. std::string data = "data: 1";
  37. bool success = google::protobuf::TextFormat::ParseFromString(data, msg);
  38. if (success) {
  39. return 0;
  40. } else {
  41. std::cerr << "Failed to parse message." << std::endl;
  42. return 2;
  43. }
  44. }
  45. std::cerr << "No matching message found." << std::endl;
  46. return 3;
  47. }