NanoPB:如何在 C++ 中处理可选字段
另请参阅:C 版本:如何在 C 中处理可选字段
NanoPB 是一个面向嵌入式系统的代码体积优化的 Protocol Buffers 实现。本文介绍如何在 C++ 中使用 NanoPB 处理可选字段(proto3 optional)。
Proto 定义
首先,创建一个包含可选字段的 .proto 文件:
optional.proto
syntax = "proto3";
package example;
message OptionalMessage {
optional uint32 id = 1;
optional string name = 2;
optional float temperature = 3;
bool active = 4; // 常规(非可选)字段
}生成 NanoPB 代码
使用 .options 文件指定字符串缓冲区大小,然后生成 NanoPB 代码:
创建 optional.options:
optional.options
example.OptionalMessage.name max_size:64然后生成:
generate_nanopb_optional.sh
protoc --nanopb_out=. optional.proto这将生成 optional.pb.h 和 optional.pb.c。
C++ 示例
下面是一个处理可选字段的完整 C++ 示例:
optional_example.cpp
#include <stdio.h>
#include <string.h>
#include "optional.pb.h"
#include "pb_encode.h"
#include "pb_decode.h"
int main() {
// 编码消息的缓冲区
uint8_t buffer[256];
size_t message_length;
// --- 编码 ---
example_OptionalMessage message = example_OptionalMessage_init_zero;
// 设置可选字段
message.id = 42;
message.has_id = true; // 重要:设置 has_* 标志
strncpy(message.name, "Sensor1", sizeof(message.name) - 1);
message.has_name = true; // 重要:设置 has_* 标志
message.temperature = 23.5f;
message.has_temperature = true; // 重要:设置 has_* 标志
// 常规字段(不需要 has_* 标志)
message.active = true;
// 创建编码流
pb_ostream_t ostream = pb_ostream_from_buffer(buffer, sizeof(buffer));
// 编码消息
if (!pb_encode(&ostream, example_OptionalMessage_fields, &message)) {
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_OptionalMessage decoded = example_OptionalMessage_init_zero;
// 创建解码流
pb_istream_t istream = pb_istream_from_buffer(buffer, message_length);
// 解码消息
if (!pb_decode(&istream, example_OptionalMessage_fields, &decoded)) {
printf("Decoding failed: %s\n", PB_GET_ERROR(&istream));
return 1;
}
// 打印解码后的值
printf("Decoded values:\n");
if (decoded.has_id) {
printf(" id: %u\n", decoded.id);
} else {
printf(" id: (not set)\n");
}
if (decoded.has_name) {
printf(" name: %s\n", decoded.name);
} else {
printf(" name: (not set)\n");
}
if (decoded.has_temperature) {
printf(" temperature: %f\n", decoded.temperature);
} else {
printf(" temperature: (not set)\n");
}
printf(" active: %s\n", decoded.active ? "true" : "false");
return 0;
}编译命令
使用 nanopb 编译该示例。NanoPB 通常通过将源文件直接包含到你的项目来使用:
compile_optional_example.sh
g++ -o optional_example optional_example.cpp optional.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_optional.py
import optional_pb2
# 读取二进制数据
with open('encoded.bin', 'rb') as f:
data = f.read()
# 解码
msg = optional_pb2.OptionalMessage()
msg.ParseFromString(data)
print("Python decoded values:")
print(f" id: {msg.id if msg.HasField('id') else '(not set)'}")
print(f" name: {msg.name if msg.HasField('name') else '(not set)'}")
print(f" temperature: {msg.temperature if msg.HasField('temperature') else '(not set)'}")
print(f" active: {msg.active}")首先,编译 Python protobuf 定义:
compile_python_optional.sh
protoc --python_out=. optional.proto然后修改 C++ 示例,将编码后的数据保存到文件:
save_encoded_optional.cpp
// 编码后,添加以下代码:
FILE *f = fopen("encoded.bin", "wb");
fwrite(buffer, 1, message_length, f);
fclose(f);缺少可选字段的示例
下面是一个某些可选字段未设置的示例:
optional_partial_example.cpp
#include <stdio.h>
#include <string.h>
#include "optional.pb.h"
#include "pb_encode.h"
#include "pb_decode.h"
int main() {
uint8_t buffer[256];
size_t message_length;
// --- 编码 ---
example_OptionalMessage message = example_OptionalMessage_init_zero;
// 只设置部分可选字段
message.id = 42;
message.has_id = true;
// name 和 temperature 未设置(has_* 标志保持为 false)
// 常规字段总是设置
message.active = true;
pb_ostream_t ostream = pb_ostream_from_buffer(buffer, sizeof(buffer));
if (!pb_encode(&ostream, example_OptionalMessage_fields, &message)) {
printf("Encoding failed: %s\n", PB_GET_ERROR(&ostream));
return 1;
}
message_length = ostream.bytes_written;
printf("Encoded %zu bytes (partial)\n", message_length);
// --- 解码 ---
example_OptionalMessage decoded = example_OptionalMessage_init_zero;
pb_istream_t istream = pb_istream_from_buffer(buffer, message_length);
if (!pb_decode(&istream, example_OptionalMessage_fields, &decoded)) {
printf("Decoding failed: %s\n", PB_GET_ERROR(&istream));
return 1;
}
printf("Decoded values:\n");
printf(" id: %s\n", decoded.has_id ? "set" : "not set");
printf(" name: %s\n", decoded.has_name ? "set" : "not set");
printf(" temperature: %s\n", decoded.has_temperature ? "set" : "not set");
printf(" active: %s\n", decoded.active ? "true" : "false");
return 0;
}要点
- 可选字段:在 proto3 中使用
optional关键字 - has_ 标志*:NanoPB 为每个可选字段生成
has_fieldname布尔标志 - 编码:同时设置字段值和
has_*标志为 true - 解码:在使用可选字段值之前检查
has_*标志 - 常规字段:非可选字段没有
has_*标志 - 默认值:未设置的可选字段具有默认值(0、空字符串等)
- 节省空间:未设置的可选字段不会包含在编码后的消息中
何时使用可选字段
- 当一个字段在不同的消息实例中可能存在也可能不存在时
- 当你想区分"未设置"和"设置为默认值"时
- 当你想通过省略未使用的字段来节省带宽时
- 当一个字段只在某些上下文中相关时
预期输出(完整示例)
optional_full_expected_output.txt
Encoded 19 bytes
Encoded data: 08 2a 12 07 53 65 6e 73 6f 72 31 1d 00 00 bc 41 30 01
Decoded values:
id: 42
name: Sensor1
temperature: 23.500000
active: true预期输出(部分示例)
optional_partial_expected_output.txt
Encoded 4 bytes (partial)
Encoded data: 08 2a 30 01
Decoded values:
id: set
name: not set
temperature: not set
active: true注意部分编码如何变得更小(4 字节对比 19 字节),因为可选字段被省略了。
更多 NanoPB 文章
- C++ 中的基本标量类型
- C 中的基本标量类型
- C++ 中的字符串类型
- C 中的字符串类型
- C++ 中的 bytes 类型
- C 中的 bytes 类型
- C 中的可选字段
- C++ 中的 repeated 字段/数组
- C 中的 repeated 字段/数组
- C++ 中的枚举
- 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