目录
源码下载
文件名:nanopb-0.4.7-linux-x86.tar.gz
地址如下:
https://jpa.kapsi.fi/nanopb/download/
编写proto文件
文件名:test.proto
syntax = "proto2";
message TestMessage
{
required string name = 1;
required uint32 age = 2;
optional fixed32 grade = 3;
}
//TestMessage.name max_size:32
编写options文件
文件名:test.options
TestMessage.name max_size:32
生成代码
参数nanopb_out指定生成代码的输出路径
./nanopb-0.4.7-linux-x86/generator-bin/protoc --nanopb_out=. test.proto
执行过后,生成如下两个文件:
test.pb.c
test.pb.h
两者内容分别如下:
test.pb.c
/* Automatically generated nanopb constant definitions */
/* Generated by nanopb-0.4.7 */
#include "test.pb.h"
#if PB_PROTO_HEADER_VERSION != 40
#error Regenerate this file with the current version of nanopb generator.
#endif
PB_BIND(TestMessage, TestMessage, AUTO)
test.pb.h
/* Automatically generated nanopb header */
/* Generated by nanopb-0.4.7 */
#ifndef PB_TEST_PB_H_INCLUDED
#define PB_TEST_PB_H_INCLUDED
#include <pb.h>
#if PB_PROTO_HEADER_VERSION != 40
#error Regenerate this file with the current version of nanopb generator.
#endif
/* Struct definitions */
typedef struct _TestMessage {
char name[32];
uint32_t age;
bool has_grade;
uint32_t grade;
} TestMessage;
#ifdef __cplusplus
extern "C" {
#endif
/* Initializer values for message structs */
#define TestMessage_init_default {"", 0, false, 0}
#define TestMessage_init_zero {"", 0, false, 0}
/* Field tags (for use in manual encoding/decoding) */
#define TestMessage_name_tag 1
#define TestMessage_age_tag 2
#define TestMessage_grade_tag 3
/* Struct field encoding specification for nanopb */
#define TestMessage_FIELDLIST(X, a) \
X(a, STATIC, REQUIRED, STRING, name, 1) \
X(a, STATIC, REQUIRED, UINT32, age, 2) \
X(a, STATIC, OPTIONAL, FIXED32, grade, 3)
#define TestMessage_CALLBACK NULL
#define TestMessage_DEFAULT NULL
extern const pb_msgdesc_t TestMessage_msg;
/* Defines for backwards compatibility with code written before nanopb-0.4.0 */
#define TestMessage_fields &TestMessage_msg
/* Maximum encoded size of messages (where known) */
#define TestMessage_size 44
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif
编写测试代码
文件名:test.c,内容如下:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#include "pb_decode.h"
#include "pb_encode.h"
#include "test.pb.h"
int main (int argc, char *argv[])
{
uint8_t buf[64];
uint8_t name[32] = {0};
size_t len;
TestMessage o = TestMessage_init_default;
TestMessage n = TestMessage_init_default;
pb_ostream_t o_stream = {0};
pb_istream_t i_stream = {0};
strcat(o.name, "Mike jordan");
o.age = 17;
o_stream = pb_ostream_from_buffer(buf, sizeof(buf));
pb_encode(&o_stream, TestMessage_fields, &o);
len = o_stream.bytes_written;
printf("len: %ld\n", len);
i_stream = pb_istream_from_buffer(buf, len);
pb_decode(&i_stream, TestMessage_fields, &n);
printf("name: %s\n", n.name);
printf("age: %u\n", n.age);
return 0;
}
编译
这里使用源码一起编译
首先将下面这些代码放入同一个目录中:
执行编译指令:
gcc test.c test.pb.c pb_common.c pb_decode.c pb_encode.c -I.