protobuf 在嵌入式ARM平台的应用(c语言版)

一、PC上安装protobuf和protobuf-c

1. 安装protobuf

  protocolbuffers 仓库地址 :https://github.com/protocolbuffers/protobuf

  本文选择下载 v21.12版本(太新版本 protobuf-c可能不支持)

$ cd protobuf-21.12
$ ./autogen.sh
$ ./configure  #默认安装路径/usr/local/
$ make 
$ sudo make install 

 

2. 安装protobuf-c

仓库地址:https://github.com/protobuf-c/protobuf-c

$ git clone https://github.com/protobuf-c/protobuf-c.git
$ cd protobuf-c
$ ./autogen.sh
$ ./configure
$ make
$ sudo make install
$ sudo ldconfig

 

会生成 /usr/local/bin/protoc-c 和  /usr/local/bin/protoc-gen-c ,用于根据.proto 生成 c 源码。

二、交叉编译protobuf-c库

#重新进入 protobuf-c 目录
$ make clean #清除之前的配置
$ ./configure --host=arm-none-linux-gnueabihf CC=arm-none-linux-gnueabihf-gcc CXX=arm-none-linux-gnueabihf-g++ --disable-protoc --prefix=$PWD/tmp
$ make 
$ make install

会生成lib和include,其中libprotobuf-c.so* 需要拷贝到ARM开发板中(如/lib下)。

三、protobuf 试用

1. 创建 msg.proto 文件

syntax = "proto3";

message MB04RSP
{
  string name = 1;
  uint32 addr = 2;
  uint32 num  = 3;
  repeated uint32 data = 4;
}

2. protoc 生成 c 代码

$ protoc --c_out=. msg.proto

结果会自动生成 msg.pb-c.c 和 msg.pb-c.h

3. 主要API

   msg.pb-c.h中列出了消息结构序列化、反序列化的API。

/* 初始化MB04RSP消息结构体 */
void   mb04_rsp__init
                     (MB04RSP         *message);

/* 将消息体 message 序列化到 out 缓冲区 ,返回序列化后字节长度 */
size_t mb04_rsp__pack
                     (const MB04RSP   *message,
                      uint8_t             *out);

/* 从缓冲区data 反序列化 到消息结构 MB04RSP, 返回结构体指针(指向内存默认为堆) */
MB04RSP *
       mb04_rsp__unpack
                     (ProtobufCAllocator  *allocator,
                      size_t               len,
                      const uint8_t       *data);

/* 释放保存反序列化返回的结构体内存 */
void   mb04_rsp__free_unpacked
                     (MB04RSP *message,
                      ProtobufCAllocator *allocator);

交叉编译app时记得链接第二节生成的 ARM平台库 libprotobuf-c.so*。

 

参考博文:  https://blog.csdn.net/zhengnianli/article/details/110914259

posted @ 2024-04-19 18:41  云的边界  阅读(580)  评论(0)    收藏  举报