proto3安装与使用

本文介绍了proto3在Windows和Linux系统的安装步骤,并通过不同demo展示了如何使用,包括创建.proto文件,生成C++代码,处理编码问题,以及利用protobuf进行文件读写、自定义类型和message嵌套、repeated字段的操作。
摘要由CSDN通过智能技术生成

windows 系统:

1.下载proto3压缩包

https://github.com/google/protobuf/releases

直接解压到一个路径即可,把bin文件夹添加到系统path里面。cmd运行protoc --version

2.新建一个demo.proto文件,cd进入文件目录,protoc  --cpp_out=.  demo.proto 。即可生成.cc和.h文件

Linux系统:

Ubuntu16.04下我的安装过程如下:

先卸载proto2

参考

ubuntu16.04有了proto2,需要先卸载,否则会导致版本冲突



sudo git clone https://github.com/google/protobuf.git
cd protobuf
sudo git submodule update --init --recursive
sudo ./autogen.sh
sudo ./configure
sudo make
sudo make check
sudo make install
sudo ldconfig # refresh shared library cache.

安装时间有点长

ubuntu@ubuntu-Super-Server:/usr/protobuf/protobuf$ sudo ldconfig
ubuntu@ubuntu-Super-Server:/usr/protobuf/protobuf$  protoc --version
libprotoc 3.9.0

使用:

参考

发现:

game.proto:13:32: Interpreting non ascii codepoint 227. 这是由于编码问题,我们重新写一下对应的行就好了。写个脚本用于批量转换:

#!/bin/bash

dir="."
cd $dir
for file in $(ls $dir | grep .proto)
    do  
        echo $file
        protoc --cpp_out=$dir $file
    done

echo "done"

对于每一个message,protobuf生成的内容主要包括:

class rsp_login : public ::google::protobuf::MessageLite
{
public:
  //每一个message类都包含以下方法供你检测或操作
  void CopyFrom(const rsp_login& from);
  void MergeFrom(const rsp_login& from);
  void Clear();                              //清除所有字段内容,并置为空状态
  bool IsInitialized() const;                //检测所有required 是否初始化
  int ByteSize() const;                      //类所占字节数
  
  //整形变量只提供获取、修改、清除
  void clear_ret();
  ::google::protobuf::int32 ret() const;
  void set_ret(::google::protobuf::int32 value);

  //自定义类类型user_info
  bool has_user_info() const;
  void clear_user_info();
  const ::pt::obj_user_info& user_info() const;
  //自定义类型,并没提供set方法,而是通过mutable_接口返回user_info的指针,可根据此指针进行赋值操作
  ::pt::obj_user_info* mutable_user_info();
  //返回user_info字段指针,将所有权移交给此指针,并将user_info字段置为empty状态
  ::pt::obj_user_info* release_user_info();
  //使用set_allocated要小心,传入的参数需要显示allocate,设置后函数内部维护此指针
  void set_allocated_user_info(::pt::obj_user_info* user_info);

  //record为repeated的类数组类型
  int record_size() const;
  void clea
  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值