protobuf repeated c++ 操作

准备

// 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 。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值