1、定义嵌套protobuffer
message ***IpaddressPair{
bytes local_ip = 1;
bytes remote_ip = 2;
}
message ***ConnectionStatus{
bool connected = 1;
bytes peer_id = 2;
***IpaddressPair ipaddr_pair = 3;
}
2、使用这个mutable_ipaddr_pair函数会在类里new一个***IpaddressPair;下面这种是正确的
//test connection_status
***ConnectionStatus connection_status_info;
connection_status_info.set_connected(true);
connection_status_info.set_peer_id("11-22-33");
***IpaddressPair *ipaddr_pair = connection_status_info.mutable_ipaddr_pair();
ipaddr_pair->set_local_ip("192.168.3.1");
ipaddr_pair->set_remote_ip("192.168.3.89");
3、解析嵌套protobuffer
***ConnectionStatus connection_status;
connection_status.ParseFromString(serilalized_connection_status);
log_d("peer_id = %s, local_ip = %s, remote_ip = %s", connection_status.peer_id().c_str(), connection_status.ipaddr_pair().local_ip().c_str(),
connection_status.ipaddr_pair().remote_ip().c_str());
下面是实例化protobuffer时犯错误:
错误原因:ipaddr_pair是局部变量,却赋值给其他对象,在connection_status_info析构时会报错
***ConnectionStatus connection_status_info;
connection_status_info.set_connected(true);
connection_status_info.set_peer_id("11-22-33");
***IpaddressPair ipaddr_pair;
connection_status_info.set_allocated_ipaddr_pair(&ipaddr_pair);
如果改成下面这种是正确的:
***IpaddressPair *ipaddr_pair = new ***IpaddressPair();
connection_status_info.set_allocated_ipaddr_pair(ipaddr_pair);