一些 protobuf 的复盘(一)—— C++写完后的验证

protobuf 真是太好用了,以后不免会多次接触,所以标题就加个(一)吧

写完之后,用C++在get一下,太麻烦了,况且我甚至都已经保存为 .pb 文件了,再去打印一下hhh麻烦

有没有直观的方法,有,太有了

“Life is short
(You need Python)-- Bruce Eckel
ANSI C++ Comitee member
[1] “Life is short, use Python” 最初是谁在什么情况下说的? - 题叶的回答 - 知乎
https://www.zhihu.com/question/20830223/answer/16322209

这里要先给你的Python环境安装 protobuf 的库:
参考这个就好,我就是按照这个跑通的:
https://blog.youkuaiyun.com/adamwu1988/article/details/56675221

再将你的 protobuf 数据类型写成 pb 文件,给一个C++代码
摘自谷歌官方文档:

{
    // 写 pb 文件
    // https://phenix3443.github.io/notebook/protobuf/basic-cpp.html
    fstream output("x.pb", ios::out | ios::trunc | ios::binary); 
    if (!message.SerializeToOstream(&output)) {
        cerr << "Failed to write address book." << endl;
        // return -1;
    }
}
`message` 就是你的 protobuf 对象

protocxxxx.proto 脚本编译为xxxx.py

看官方的demo,是最简单有效的:
https://developers.google.com/protocol-buffers/docs/pythontutorial

假设你的协议是这样定义的:

syntax = "proto2";

package tutorial;

message Person {
  optional string name = 1;
  optional int32 id = 2;
  optional string email = 3;
}

message AddressBook {
  repeated Person people = 1;
}

(修改自谷歌官方文档)

则新建一个python脚本:

import xxxx as pb

message = pb.AddressBook()     # 这里要根据你的改

print(message)   # 这里只会打印一个回车

with open("x.pb", "rb") as f:
    message.ParseFromString(f.read())  # python 读入 pb 文件的API
    
print(message)   # 这里会打印 x.pb 文件里的详细信息

这是我自己的例子的打印结果,就hin直观:

lane_info {
  dims: 2
  lanes {
    cid: 1
    score: 0.5935865
    sub_cid: 31
    sub_score: 0.0
    points: 524.8493
	...
    points: 1676.2792
    coefs: 0.0
  }
  lanes {
    cid: 1
    score: 0.4397558
    sub_cid: 31
    sub_score: 0.0
    points: 462.73105
    points: 1524.0184
    coefs: 0.0
  }
}

最后再放一张图吧:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值