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


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

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

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

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

    这里要先给你的Python环境安装 protobuf 的库:
    参考这个就好,我就是按照这个跑通的:
    https://blog.csdn.net/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 对象
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    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;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    (修改自谷歌官方文档)

    则新建一个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 文件里的详细信息
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    这是我自己的例子的打印结果,就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
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

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

  • 相关阅读:
    MySQL之误删数据如何处理
    Nginx+Keepalived
    手把手带你学SQL—牛客网SQL 别名
    Java服务频繁挂掉,内存溢出
    系统性认知网络安全
    LabVIEW-数据采集
    反无人机系统
    LeetCode 1417. 重新格式化字符串
    HackTheBox Ambassador 枚举获得用户shell,git consul API提权
    八股文-TCP的四次挥手
  • 原文地址:https://blog.csdn.net/HaoZiHuang/article/details/126771605