4

I have code which has multiple complex C++ data structures that I want to save to disk to later deserialize to be used again. Let's put an example to easily understand what I'm trying to do. I have the following C++ struct:

struct myCstruct
{
    int id;
    OtherStructType ot;
    std::vector<std::string> my_array;
    std::vector<StructType_2> my_other_array;
};

I wrote the equivalent .proto files to represent myCstruct:

syntax = "proto3";
import "OtherStructType.proto"; // OtherStructType proto code is here
import "3drStructType.proto"; // 3drStructType proto code is here
package my_ns;

message myCstruct{
    int32 id = 1;
    OtherStructType ot = 2;
    repeated string my_array = 3;
    repeated StructType_2 my_other_array = 4;
}

Somewhere in my code I have a variable foo referencing an instance of myCstruct. How can I now cast var to a type my_ns::myCstruct given that I've compiled the .proto files and included the generated C++ files in my project?:

struct myCstruct var = some_func();
my_ns::myCstruct proto_struct;
// How can I dump the content of var into proto_struct???

I know protobuf creates methods to set attributes but I want to dump the entire content of the C++ struct in the protobuf class instance. I don't want to:

struct myCstruct var = some_func();
my_ns::myCstruct proto_struct;
proto_struct_set_id(var.id);
proto_struct_set_ot(var.ot);
...

Any help is appreciated.

user1618465
  • 1,813
  • 2
  • 32
  • 58
  • 2
    We ended up copying field by field, but I would be very interested in a better solution. I assume the problem is that not all protobuf features have an obvious equivalent in C++, like maybe "oneof". In other words, I assume this limitation is a design decision. A pitty for people that use protobuf just for simple types. – P. Saladin Feb 07 '21 at 14:11
  • I would be disappointed with protobuf if there is no way to do it at once. As long as the struct types can be casted or constructed to the protobuf types I don't see why this should not theoretically be done. – user1618465 Feb 07 '21 at 19:37
  • See also [Conversion between C structs (C++ POD) and google protobufs](https://stackoverflow.com/questions/13073930/conversion-between-c-structs-c-pod-and-google-protobufs), which is about POD types, no "complex" types as in your question. But even that simpler case seems to have no (easy) solution. – P. Saladin Feb 07 '21 at 19:55
  • That question is more focused on autogenerating the .proto files from an existent C++ structure. My question is about casting (or transcoding) the C++ data structure to the protobuf class. – user1618465 Feb 07 '21 at 20:20
  • I don't think it's possible like what you said, the api reference doesn't make any comments for the same. Also it seems more like converting from a class to another, (albeit the first being generated from other), so constructor seems the only correct way to me... And it's not available :( – AdityaG15 Jul 15 '21 at 20:24

0 Answers0