准备
// Obstacle.proto
syntax = "proto3";
package test;
import "google/protobuf/any.proto";
message Obstacle {
int32 id = 1;
int32 x = 2;
int32 y = 3;
}
// fusion.proto
syntax = "proto3";
package test;
import "google/protobuf/any.proto";
import "obstacle.proto";
package test;
message Fusion {
int32 id = 1;
repeated Obstacle obstacleList = 2;
}
操作
test::Fusion fusion1, fusion2;
fusion1.set_id(1);
test::Obstacle *obstacle = fusion1.add_obstaclelist(),
*obstacle1 = fusion1.add_obstaclelist(),
*obstacle2 = fusion1.add_obstaclelist();
obstacle->set_id(100);
obstacle1->set_id(101);
obstacle2->set_id(102);
int byteSize = fusion1.ByteSize();
std::cout << "fusion1 bytesize:" << byteSize << std::endl;
char buff[byteSize];
fusion1.SerializeToArray(buff, byteSize);
if (fusion2.ParseFromArray(buff, byteSize))
{
std::cout << "good fusion2" << std::endl
<< "id:" << fusion2.id() << std::endl
<< "obs:" << fusion2.obstaclelist_size() << std::endl
<< "id 0:" << fusion2.obstaclelist(0).id() << std::endl
<< "id 2:" << fusion2.obstaclelist(2).id() << std::endl;
}
小结
test::Obstacle *obstacle = fusion1.add_obstaclelist()里的obstacle示例不能在代码里手动delete 。