嵌入式Linux Protocol Buffer 的使用

1、下载源码

git  clone https://github.com/protocolbuffers/protobuf.git

下载特定版本的源码

git clone -b 4.0.x http://github.com/protocolbuffers/protobuf.git

2、编译生成库和工具

cd protobuf
mkdir build
cmake ..
//cmake -Dprotobuf_BUILD_TESTS=OFF .. -DCMAKE_TOOLCHAIN_FILE=../arm-linux-debug.toolchain.cmake
make -j8
make instatll DESTDIR=./out

3、生成C++文件

proto文件

package lm;
 
message helloworld
 
{
 
   required int32     id = 1;  // ID
 
   required string    str = 2;  // str
 
   optional int32     opt = 3;  //optional field
 
}

生成对应的protobuf结构程序

./protoc --proto_path=./src --cpp_out=./src ./src/packageName.MessageName.proto

4、使用示例

write

#include 
#include   // 添加这一行来包含fstream定义
#include "packageName.MessageName.pb.h"
using namespace std;
int main(void)
{
    lm::helloworld msg1;
    msg1.set_id(101);
    msg1.set_str("hello");
    // 使用局部对象自动管理资源
    {
        fstream output("./log", ios::out | ios::trunc | ios::binary);
        if (!output.is_open()) {
            cerr << "Failed to open file for writing." << endl;
            return -1;
        }
        if (!msg1.SerializeToOstream(&output)) {
            cerr << "Failed to write msg." << endl;
            return -1;
        }
    } // 文件在此处自动关闭
    return 0;
}

read

#include 
#include   // 添加这一行来包含fstream定义
#include "packageName.MessageName.pb.h"

using namespace std;
void ListMsg(const lm::helloworld & msg) {
  cout << msg.id() << endl;
  cout << msg.str() << endl;
 }
 
int main(int argc, char* argv[]) {
  lm::helloworld msg1;
  {
    fstream input("./log", ios::in | ios::binary);
    if (!msg1.ParseFromIstream(&input)) {
      cerr << "Failed to parse address book." << endl;
      return -1;
    }
  }
  ListMsg(msg1);
 }

分别编译生成执行文件

g++ read.cpp packageName.MessageName.pb.cc -o read -I../out/usr/local/include ../out/usr/local/lib/libprotobufd.a ../out/usr/local/lib/libprotocd.a -latomic

你可能感兴趣的:(linux,网络协议)