1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
| using namespace google::protobuf; using namespace google::protobuf::compiler;
class DynamicGenerator { public:
DynamicGenerator(const std::string &disk_path,const std::string &proto_name) : m_factory(new DynamicMessageFactory), source(new DiskSourceTree) { source->MapPath("", disk_path); importer.reset(new Importer(&*source, {})); importer->Import(proto_name); pool = importer->pool();
} template<typename ... Types> Message *paramToMessage(const Descriptor *type, Types ... params) {
const Message *tempo = m_factory->GetPrototype(type); Message *message = tempo->New();
const Reflection *reflection = message->GetReflection();
if (sizeof...(params) > 0) addValues(input, reflection, message, params...);
field_id = 1;
return message; }
private: const DescriptorPool *pool; std::unique_ptr<DynamicMessageFactory> m_factory; std::unique_ptr<DiskSourceTree> source; std::unique_ptr<Importer> importer;
int field_id = 1;
template<typename Type> void addValues(const Descriptor *input, const Reflection *reflection, Message *message, const Type ¶m) {
auto field = input->FindFieldByNumber(field_id);
if (field == nullptr) { std::cout << "Invalid field_id.\n"; }
if constexpr(std::is_same_v<Type, std::string> || std::is_same_v<Type, const char *>) { reflection->SetString(message, field, param); } else if constexpr (std::is_same_v<Type, int>) { reflection->SetInt32(message, field, param); } else if constexpr(std::is_same_v<Type, float>) { reflection->SetFloat(message, field, param); } else if constexpr(std::is_same_v<Type, double>) { reflection->SetDouble(message, field, param); } else { std::cout << "Unknown Type: " << typeid(param).name() << "\n"; }
field_id++;
}
template<typename Type, typename ...Types> void addValues(const Descriptor *input, const Reflection *reflection, Message *message, const Type ¶m, const Types &... params) {
addValues(input, reflection, message, param);
addValues(input, reflection, message,params...);
} };
|