zoukankan      html  css  js  c++  java
  • Google的Protobuf安装及使用笔记一

    一、下载及安装

    protobuf

    项目主页:http://code.google.com/p/protobuf/

    下载:http://code.google.com/p/protobuf/downloads/list protobuf-2.4.1.tar.gz

    解压后进入protobuf-2.4.1目录进行安装:

    1、./configure(注:默认可能会安装在/usr/local目录下,可以加--prefix=/usr来指定安装到/usr/lib下,可以免去路径的设置,路径设置见Linux命令pkg-config

    2、make

    3、make check

    4、make install(需要超级用户root权限)

    二、使用

    1、写proto文件,定义消息具体格式。如:helloworld.proto

    package lm;

    message helloworld

    {

    required int32 id = 1;//ID

    required string str = 2;//str

    optional int32 opt = 3;//optional field

    }

    2、使用protoc来编译生成对应语言的文件

    --cpp_out:表示输出c++语言使用格式,--java_out,--python_out等,其他第三方的插件:Third-Party Add-ons for Protocol Buffers

    此时会生成helloworld.pb.h及helloworld.pb.cc两个文件

    3、Write A message

     

    View Code
    #include "helloworld.pb.h"
    #include
    <iostream>
    #include
    <fstream>
    #include
    <string>

    using namespace std;

    int main(void)
    {
    lm::helloworld msg1;
    msg1.set_id(
    101);
    msg1.set_str(
    "hello");

    string test;
    msg1.SerializeToString(
    &test);
    cout
    <<"Serialized size="<< test.length() << ",content=" << test << endl;

    // write the new address book back to disk.
    fstream output("./log", ios::out | ios::trunc | ios::binary);
    if (!msg1.SerializeToOstream(&output))
    {
    cerr
    <<"Failed to write msg."<<endl;
    return -1;
    }
    lm::helloworld msg;
    msg.ParseFromString(test);
    cout
    <<"Id:"<<msg.id()<<endl;
    cout
    <<"Str:"<<msg.str()<<endl;
    return 0;
    }

      

    4、Read A message

    View Code
    #include<iostream>
    #include
    <fstream>
    #include
    "helloworld.pb.h"

    using namespace std;

    int main(void)
    {
    lm::helloworld msg;
    fstream input(
    "./log", ios::in | ios::binary);
    if (!input)
    {
    cout
    <<"log file not found."<<endl;
    }
    else if(!msg.ParseFromIstream(&input))
    {
    cerr
    <<"Failed to parse helloworld."<<endl;
    return -1;
    }
    cout
    <<"id:"<<msg.id()<<endl;
    cout
    <<"str:"<<msg.str()<<endl;
    google::protobuf::ShutdownProtobufLibrary();
    return 0;
    }

      

    5、编译及运行

    g++ -g -o Writer helloworld.pb.cc writermessage.cpp `pkg-config --cflags --libs protobuf`

    g++ -g -o Reader helloworld.pb.cc Readermessage.cpp `pkg-config --cflags --libs protobuf`

  • 相关阅读:
    双重标准,我该怎么解决
    今天突然点开一个网页
    反省
    (无)
    (无)
    GetModuleHandleW 分析
    关于逆向360相关的一点感想
    OpenGL的编译和使用
    360 补天平台,也没个什么人啊。。。
    openssl编译方法
  • 原文地址:https://www.cnblogs.com/coderyoyo/p/google_protobuf_tutorial.html
Copyright © 2011-2022 走看看