Protobuf协议C版本(Nanopb)使用方法

【Protobuf官方协议不支持C语言版本,那么就不太适用于嵌入式开发,所以需要使用C 语言版本的Protobuf协议】

1.Nanopb的下载地址:Nanopb - protocol buffers with small code size (jpa.kapsi.fi)

点击下方标注的地方进入下载页面

        之后根据自己电脑的操作系统选择不同的下载包

        protobuf协议需要一个.proto的文件,通过Nanopb中的protoc工具就可以根据这个.proto文件分别生成一个.c和.h文件,这样我们就可以在C中使用。
        下面是protoc工具的配置(把改工具的地址添加到环境变量中)
        (1)把下载的nanopb解压,protoc工具在其generator-bin文件夹中
              

        (2)在搜索框中搜索”高级系统配置“,之后打开按照下面步骤配置:

点击”环境变量“,之后选中系统变量(S)中的Path,之后点击编辑,会打开

(3)以上就完成了Nanopb的配置,下面我们演示如果用protoc工具生成.c和.h文件
        首先先创建一个.proto文件,之后保存
        

2.以上是Nanopb的配置、.c和.h文件的生成,下面是具体使用方法:

protobuf使用时需要下面这些文件:如果使用到string类型的数据还需要pb_string.c和pb_string.h这两个文件,源码如下:

#ifndef DEVICE_SDK_PB_STRING_H
#define DEVICE_SDK_PB_STRING_H

#include "pb.h"
#include "pb_common.h"
#include "pb_encode.h"
#include "pb_decode.h"
bool write_string(pb_ostream_t *stream, const pb_field_t *field, void *const *arg);

bool read_string(pb_istream_t *stream, const pb_field_t *field, void **arg);

#endif //DEVICE_SDK_PB_STRING_H
#include "pb_string.h"

/**
 编码的回调函数
 **/
bool write_string(pb_ostream_t *stream, const pb_field_t *field, void *const *arg) {
    char *str = *arg;
    if (!pb_encode_tag_for_field(stream, field))
        return false;

    return pb_encode_string(stream, (uint8_t *) str, strlen(str));
}

/**
 解码回调函数
 **/
bool read_string(pb_istream_t *stream, const pb_field_t *field, void **arg) {
    int i = 0;
    char *tmp = *arg;
    while (stream->bytes_left) {
        uint64_t value;
        if (!pb_decode_varint(stream, &value))
            return false;
        *(tmp + i) = value;
        i++;
    }
    return true;
}

下面是nanopb中的官方dmeo:

可参考:嵌入式大杂烩周记第 9 期:nanopb - 知乎 (zhihu.com)
nanopb关于string类型的处理 - 简书 (jianshu.com)

  • 5
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值