NanoPB:如何在 C++ 中处理嵌套消息
另请参阅:C 版本:如何在 C 中处理嵌套消息
NanoPB 是一个面向嵌入式系统的代码体积优化的 Protocol Buffers 实现。本文介绍如何在 C++ 中使用 NanoPB 处理嵌套消息。
Proto 定义
首先,创建一个包含嵌套消息的 .proto 文件:
nested.proto
syntax = "proto3";
package example;
message Address {
string street = 1;
string city = 2;
string country = 3;
}
message Person {
string name = 1;
uint32 age = 2;
Address address = 3;
}生成 NanoPB 代码
使用 .options 文件指定字符串缓冲区大小,然后生成 NanoPB 代码:
创建 nested.options:
nested.options
example.Address.street max_size:64
example.Address.city max_size:32
example.Address.country max_size:32
example.Person.name max_size:64然后生成:
generate_nanopb_nested.sh
protoc --nanopb_out=. nested.proto这将生成 nested.pb.h 和 nested.pb.c。
C++ 示例
下面是一个处理嵌套消息的完整 C++ 示例:
nested_example.cpp
#include <stdio.h>
#include <string.h>
#include "nested.pb.h"
#include "pb_encode.h"
#include "pb_decode.h"
int main() {
// 编码消息的缓冲区
uint8_t buffer[256];
size_t message_length;
// --- 编码 ---
example_Person person = example_Person_init_zero;
// 设置嵌套消息的值
strncpy(person.name, "John Doe", sizeof(person.name) - 1);
person.has_address = true;
strncpy(person.address.street, "123 Main St", sizeof(person.address.street) - 1);
strncpy(person.address.city, "Springfield", sizeof(person.address.city) - 1);
strncpy(person.address.country, "USA", sizeof(person.address.country) - 1);
// 创建编码流
pb_ostream_t ostream = pb_ostream_from_buffer(buffer, sizeof(buffer));
// 编码消息
if (!pb_encode(&ostream, example_Person_fields, &person)) {
printf("Encoding failed: %s\n", PB_GET_ERROR(&ostream));
return 1;
}
message_length = ostream.bytes_written;
printf("Encoded %zu bytes\n", message_length);
// 打印编码数据的十六进制转储
printf("Encoded data: ");
for (size_t i = 0; i < message_length; i++) {
printf("%02x ", buffer[i]);
}
printf("\n");
// --- 解码 ---
example_Person decoded = example_Person_init_zero;
// 创建解码流
pb_istream_t istream = pb_istream_from_buffer(buffer, message_length);
// 解码消息
if (!pb_decode(&istream, example_Person_fields, &decoded)) {
printf("Decoding failed: %s\n", PB_GET_ERROR(&istream));
return 1;
}
// 打印解码后的值
printf("Decoded values:\n");
printf(" name: %s\n", decoded.name);
printf(" age: %u\n", decoded.age);
printf(" address:\n");
printf(" street: %s\n", decoded.address.street);
printf(" city: %s\n", decoded.address.city);
printf(" country: %s\n", decoded.address.country);
return 0;
}编译命令
使用 nanopb 编译该示例。NanoPB 通常通过将源文件直接包含到你的项目来使用:
compile_nested_example.sh
g++ -o nested_example nested_example.cpp nested.pb.c pb_common.c pb_encode.c pb_decode.c -I.**注意:**NanoPB 源文件(pb_common.c、pb_encode.c、pb_decode.c)需要直接与你的项目一起编译。你可以从 NanoPB GitHub 仓库 获取这些文件。
Python 测试脚本
为了验证编码,你可以使用 Python 的 protobuf 库:
test_nested.py
import nested_pb2
# 读取二进制数据
with open('encoded.bin', 'rb') as f:
data = f.read()
# 解码
msg = nested_pb2.Person()
msg.ParseFromString(data)
print("Python decoded values:")
print(f" name: {msg.name}")
print(f" age: {msg.age}")
print(f" address:")
print(f" street: {msg.address.street}")
print(f" city: {msg.address.city}")
print(f" country: {msg.address.country}")首先,编译 Python protobuf 定义:
compile_python_nested.sh
protoc --python_out=. nested.proto然后修改 C++ 示例,将编码后的数据保存到文件:
save_encoded_nested.cpp
// 编码后,添加以下代码:
FILE *f = fopen("encoded.bin", "wb");
fwrite(buffer, 1, message_length, f);
fclose(f);可选嵌套消息示例
下面是一个包含可选嵌套消息的示例:
nested_optional.proto
syntax = "proto3";
package example;
message Address {
string street = 1;
string city = 2;
}
message Person {
string name = 1;
optional Address address = 2;
}创建 nested_optional.options:
nested_optional.options
example.Address.street max_size:64
example.Address.city max_size:32
example.Person.name max_size:64nested_optional_example.cpp
#include <stdio.h>
#include <string.h>
#include "nested_optional.pb.h"
#include "pb_encode.h"
#include "pb_decode.h"
int main() {
uint8_t buffer[256];
size_t message_length;
// --- 编码 ---
example_Person person = example_Person_init_zero;
strncpy(person.name, "Jane Doe", sizeof(person.name) - 1);
// 设置可选嵌套消息
strncpy(person.address.street, "456 Oak Ave", sizeof(person.address.street) - 1);
strncpy(person.address.city, "Boston", sizeof(person.address.city) - 1);
person.has_address = true; // 重要:设置 has_* 标志
pb_ostream_t ostream = pb_ostream_from_buffer(buffer, sizeof(buffer));
if (!pb_encode(&ostream, example_Person_fields, &person)) {
printf("Encoding failed: %s\n", PB_GET_ERROR(&ostream));
return 1;
}
message_length = ostream.bytes_written;
printf("Encoded %zu bytes\n", message_length);
// --- 解码 ---
example_Person decoded = example_Person_init_zero;
pb_istream_t istream = pb_istream_from_buffer(buffer, message_length);
if (!pb_decode(&istream, example_Person_fields, &decoded)) {
printf("Decoding failed: %s\n", PB_GET_ERROR(&istream));
return 1;
}
printf("Decoded values:\n");
printf(" name: %s\n", decoded.name);
if (decoded.has_address) {
printf(" address:\n");
printf(" street: %s\n", decoded.address.street);
printf(" city: %s\n", decoded.address.city);
} else {
printf(" address: (not set)\n");
}
return 0;
}要点
- 嵌套消息:消息可以将其他消息作为字段包含
- 初始化:使用
*_init_zero初始化外部和嵌套消息 - 编码:直接设置嵌套消息字段,然后编码外部消息
- 解码:解码外部消息,嵌套消息会自动解码
- 可选嵌套:使用
optional关键字并设置has_*标志 - 结构:嵌套消息提供层次化的数据组织
- 缓冲区大小:在 .options 文件中为所有字符串字段指定缓冲区大小
何时使用嵌套消息
- 当你有层次化或分组的数据时
- 当你想复用消息定义时
- 当你需要将相关字段组织在一起时
- 当你想提高消息的可读性时
- 当你有复杂的数据结构时
预期输出
nested_expected_output.txt
Encoded 35 bytes
Encoded data: 0a 08 4a 6f 68 6e 20 44 6f 65 10 1e 1a 1b 0a 0b 31 32 33 20 4d 61 69 6e 20 53 74 12 08 4e 65 77 20 59 6f 72 6b 1a 03 55 53 41
Decoded values:
name: John Doe
age: 30
address:
street: 123 Main St
city: New York
country: USA预期输出(可选嵌套)
nested_optional_expected_output.txt
Encoded 27 bytes
Decoded values:
name: Jane Doe
address:
street: 456 Oak Ave
city: Boston更多 NanoPB 文章
- C++ 中的基本标量类型
- C 中的基本标量类型
- C++ 中的字符串类型
- C 中的字符串类型
- C++ 中的 bytes 类型
- C 中的 bytes 类型
- C++ 中的可选字段
- C 中的可选字段
- C++ 中的 repeated 字段/数组
- C 中的 repeated 字段/数组
- C++ 中的枚举
- C 中的枚举
- C 中的嵌套消息
- C++ 中的 oneof/union 类型
- C 中的 oneof/union 类型
- C++ 中的自定义数组转换器
- C 中的自定义数组转换器
Check out similar posts by category:
Embedded, C/C++, Protocol Buffers
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow