问题
Is there a way to obtain a simple struct from protocol buffers message in C++? i.e.
struct PlainFoo {
int32_t bar;
float baz;
};
from
message Foo {
required int32 bar = 1;
required float baz = 2;
}
I obtain some data over network in a protocol buffer and I'd like to be able to add it to other similar data and store it in a compact representation for internal use without having to basically copy the message declaration in my code.
I know I can use the generated message class itself, but it has bunch of internal members that I'd prefer not having to move around.
The messages in question only have required fields.
回答1:
I'm not aware of a C++ protobuf library that would generate plain structures, but there are C libraries that can be used in C++ code also. At least nanopb and pbtools generate simple structs:
/* nanopb */ typedef struct _Foo { int32_t bar; float baz; } Foo;
/* pbtools */ struct Foo_t { int32_t bar; float baz; };
With nanopb, you also have the option of using PB_BIND() to connect the tag number definitions from .proto
file to a structure that is defined in your own code. This can be useful if you want to decouple your code from the interface specifications, and allows e.g. adding extra fields that are not serialized.
来源:https://stackoverflow.com/questions/64558881/plain-struct-from-protocol-buffer-message