I am learning C++ ProtoBuf.
I have the following struct which I need to serialize:
enum phonetype
{
DESKPHONE,
MOBILE,
WIRELESSPHONE
};
struct phonenumber
{
int ptype;
string number;
};
struct address
{
string addr1;
string addr2;
};
struct college
{
string collegename;
string collegeaddress;
};
struct student
{
int id;
string name;
double age;
string email;
struct phonenumber phoneN;
struct address addr;
struct college col;
};
I have initialized the struct as follows:
student stud = {123, "Stud_1", 30, "none",
{MOBILE, "123456789"},
{"Boston, US", "None"},
{"Boston college", "Boston"}};
Now I would like to create a serialized string of this struct for which I have written the following .proto
file:
syntax = "proto2";
message studentP
{
required int32 id = 1;
required string name = 2;
required double age = 3;
optional string email = 4;
message phonenumberP
{
required int32 ptype = 1;
required string number = 2;
}
message addressP {
required string addr1 = 1;
optional string addr2 = 2;
}
message collegeP {
required string collegename = 1;
optional string collegeaddress = 2;
}
}
In my C++ code, I am setting the proto obj values as follows:
studentP studObj;
studObj.set_name(stud.name);
studObj.set_eid(stud.id);
studObj.set_age(stud.age);
studentP::phonenumberP *phone;
phone->set_ptype(stud.phoneN.ptype);
phone->set_number(stud.phoneN.number);
studentP::addressP *addr;
addr->set_addr1(stud.addr.addr1);
addr->set_addr2(stud.addr.addr2);
studentP::collegeP *coll;
coll->set_collegename(stud.col.collegename);
coll->set_collegeaddress(stud.col.collegeaddress);
string student_str;
studObj.SerializeToString(&student_str);
Above I have separately set the values for the internal structs of class studentP
.
How do I set the values for the internal structure of studentP
object studObj
?
Do I need to call SerializeToString
for each internal struct?