protobuf的使用

一、protobuf的下载安装

1、解压压缩包:unzip protobuf-master.zip
2、进入解压后的文件夹:cd protobuf-master
3、安装所需工具:sudo apt-get install autoconf automake libtool curl make g++ unzip
4、自动生成configure配置文件:./autogen.sh
5、配置环境:./configure
6、编译源代码(时间比较长):make
7、安装:sudo make install
8、刷新动态库:sudo ldconfig

 二、protobuf文件test.proto的实现

syntax="proto3";//version

package fixbug;       //namespace

message ResultCode
{
    int32 errcode=1;
    bytes errmsg=2; 
}

//request  message  type
message LoginRequest
{
bytes name=1;
bytes pwd=2;
}

//response message type
message LoginResponse
{
    int32 errcode=1;
    string errmsg=2;
    bool sucess=3;
}

message GetFriendListRequest
{
    uint32  userid=1;
}

message user
{
    bytes name=1;    //string 
    uint32 age=2;
    enum Sex{
        MAN=0;
        WOMAN=1;
    }
    Sex sex=3;       //3 members
}

//list message 
message GetFriendListResponse
{
   ResultCode result=1;
   repeated  user friendlist=2;       //list type
}

三、编译test.proto文件

protoc  test.proto --cpp_out=./      

生成test.pb.cc  test.pb.h文件

 四、编写主函数

#include "test.pb.h"
using namespace std;

using   namespace  fixbug;
int main()
{
    /*LoginResponse  rsp;      //当一个message中包含另一个message时,例如LoginResponse 包含 
                               //了ResultCode,那么将ResultCode指针接收rsp.mutable_result()
    ResultCode*rc=rsp.mutable_result();
    rc->set_error_code(1);
    rc->set_error_message("error");
    */
    GetFriendListResponse  rsp;
    ResultCode*rc=rsp.mutable_result();
    rc->set_errcode(1);
    user* user1=rsp.add_friendlist();//add list member
    user1->set_name("zhansan");    
    user1->set_age(20);
    user1->set_sex(user::MAN);
    std::cout<<rsp.friendlist_size()<<std::endl;

}
/*
int main()
{
    LoginRequest req;
    req.set_name("zhansan");
    req.set_pwd("123456");
    string send_str;
    if(req.SerializeToString(&send_str)==true)      //序列化,将req的内容全部序列化为字符串
    {
        std::cout<<send_str<<std::endl;
    }

    LoginRequest reqs;
    if(reqs.ParseFromString(send_str))              //反序列化,将字符串内容反序列到reqs中
    {
        cout<<reqs.name()<<std::endl;
        cout<<reqs.pwd()<<std::endl;
    }
    return 0;
    
}
*/

五、编译成可执行文件a.out

g++   main.cc  test.pb.cc   -lprotobuf

 

  • 6
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值