栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

protobuf入门

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

protobuf入门

编译
sudo apt-get install autoconf automake libtool curl make g++ unzip
./configure --prefix=/home/work/tool/protobuf-3.18.0-install
sudo make
sudo make check(可忽略)
sudo make install


进入bin目录,可以看到编译出来的protoc,这个工具是用来将.proto编译成目标语言的序列化代码

demo测试

创建工程

include 目录是上面编译出来的,直接拷贝过来
libprotobuf.a 是上面编译出来的lib目录下的静态库
msg.proto 自定义数据结构,定义如下

package Im;
message Content
{
    required int32 id = 1;
    required string str = 2;
    optional int32 opt = 3;
}

接下来就可以将msg.proto编译出c++代码,使用的工具就是上面编译出来的bin目录下的文件

~/work/tool/protobuf-3.19.0-install/bin/protoc --cpp_out=./ msg.proto

编译后生成两个文件

编写测试demo
#include 
#include 
#include "msg.pb.h"

//演示了将数据机构序列化 保存到./log文件中
//g++ -o main main.cpp msg.pb.cc -Iinclude -L. -lprotobuf

int main()
{
    Im::Content msg1;
    msg1.set_id(123);
    msg1.set_opt(465);
    msg1.set_str("hello world");
    std::fstream output("./log",std::ios::out|std::ios::trunc|std::ios::binary);
    if(!msg1.SerializeToOstream(&output))
    {
        std::cerr << "err output!" << std::endl;
        return -1;
    }
    return 0;
}
编写反序列化demo
#include 
#include 
#include "msg.pb.h"

//g++ -o deserialize deserialize.cpp msg.pb.cc -Iinclude -L. -lprotobuf

int main()
{
    Im::Content msg;
    std::fstream input("./log",std::ios::in|std::ios::binary);
    if(!msg.ParseFromIstream(&input))
    {
        std::cerr << "parse err!" << std::endl;
        return -1;
    }
    std::cout << "" << msg.id() << std::endl;
    std::cout << "" << msg.str() << std::endl;  
    return 0;    
}
执行结果

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/347786.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号