我正在学习C ++ ProtoBuf。
我需要序列化以下结构:
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;
};
我已经按如下所示初始化了结构:
student stud = {123,"Stud_1",30,"none",{MOBILE,"123456789"},{"Boston,US","None"},{"Boston college","Boston"}};
现在,我想为此结构创建一个序列化的字符串,为此我编写了以下.proto
文件:
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;
}
}
在我的C ++代码中,我将原始obj值设置如下:
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);
以上,我分别设置了类studentP
的内部结构的值。
如何为studentP
对象studObj
的内部结构设置值?
我需要为每个内部结构调用SerializeToString
吗?