NanoPB:如何在 C++ 中处理基本标量类型
另请参阅:C 版本:如何在 C 中处理基本标量类型
NanoPB 是一个面向嵌入式系统的代码体积优化的 Protocol Buffers 实现。本文介绍如何在 C++ 中使用 NanoPB 处理基本标量类型(整数、浮点数、布尔值)。
Proto 定义
首先,创建一个包含基本标量类型的简单 .proto 文件:
scalars.proto
syntax = "proto3";
package example;
message ScalarMessage {
uint32 uint32_value = 1;
uint64 uint64_value = 2;
int32 int32_value = 3;
int64 int64_value = 4;
float float_value = 5;
bool bool_value = 6;
}生成 NanoPB 代码
使用 nanopb 生成器生成 C++ NanoPB 代码:
generate_nanopb_scalars.sh
protoc --nanopb_out=. scalars.proto这将生成 scalars.pb.h 和 scalars.pb.c。
C++ 示例
以下是一个编码和解码消息的完整 C++ 示例:
scalars_example.cpp
#include <stdio.h>
#include <string.h>
#include "scalars.pb.h"
#include "pb_encode.h"
#include "pb_decode.h"
int main() {
// 编码消息的缓冲区
uint8_t buffer[128];
size_t message_length;
// --- 编码 ---
example_ScalarMessage message = example_ScalarMessage_init_zero;
// 设置字段值
message.uint32_value = 42;
message.uint64_value = 1234567890ULL;
message.int32_value = -100;
message.int64_value = -9876543210LL;
message.float_value = 3.14159f;
message.bool_value = true;
// 创建编码流
pb_ostream_t ostream = pb_ostream_from_buffer(buffer, sizeof(buffer));
// 编码消息
if (!pb_encode(&ostream, example_ScalarMessage_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_ScalarMessage decoded = example_ScalarMessage_init_zero;
// 创建解码流
pb_istream_t istream = pb_istream_from_buffer(buffer, message_length);
// 解码消息
if (!pb_decode(&istream, example_ScalarMessage_fields, &decoded)) {
printf("Decoding failed: %s\n", PB_GET_ERROR(&istream));
return 1;
}
// 打印解码后的值
printf("Decoded values:\n");
printf(" uint32_value: %u\n", decoded.uint32_value);
printf(" uint64_value: %llu\n", (unsigned long long)decoded.uint64_value);
printf(" int32_value: %d\n", decoded.int32_value);
printf(" int64_value: %lld\n", (long long)decoded.int64_value);
printf(" float_value: %f\n", decoded.float_value);
printf(" bool_value: %s\n", decoded.bool_value ? "true" : "false");
return 0;
}编译命令
使用 nanopb 编译示例。NanoPB 通常通过将源文件直接包含到项目中来使用:
compile_scalars_example.sh
g++ -o scalars_example scalars_example.cpp scalars.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_scalars.py
import scalars_pb2
# 读取二进制数据
with open('encoded.bin', 'rb') as f:
data = f.read()
# 解码
msg = scalars_pb2.ScalarMessage()
msg.ParseFromString(data)
print("Python decoded values:")
print(f" uint32_value: {msg.uint32_value}")
print(f" uint64_value: {msg.uint64_value}")
print(f" int32_value: {msg.int32_value}")
print(f" int64_value: {msg.int64_value}")
print(f" float_value: {msg.float_value}")
print(f" bool_value: {msg.bool_value}")首先,编译 Python protobuf 定义:
compile_python_scalars.sh
protoc --python_out=. scalars.proto然后修改 C++ 示例,将编码后的数据保存到文件:
save_encoded_scalars.cpp
// 编码后,添加以下代码:
FILE *f = fopen("encoded.bin", "wb");
fwrite(buffer, 1, message_length, f);
fclose(f);要点
- 使用
*_init_zero以默认值初始化消息 pb_ostream_from_buffer创建用于编码的输出流pb_istream_from_buffer创建用于解码的输入流pb_encode和pb_decode处理实际的编码/解码- 检查返回值并使用
PB_GET_ERROR进行错误处理
预期输出
scalars_expected_output.txt
Encoded 28 bytes
Encoded data: 08 2a 10 d2 95 89 04 18 9c ff ff ff ff ff ff ff 01 20 c6 ef be ad de 05 2d 15 49 0e 40 30 01
Decoded values:
uint32_value: 42
uint64_value: 1234567890
int32_value: -100
int64_value: -9876543210
float_value: 3.141590
bool_value: true更多 NanoPB 文章
- C 中的基本标量类型
- C++ 中的字符串类型
- C 中的字符串类型
- C++ 中的 bytes 类型
- C 中的 bytes 类型
- C++ 中的可选字段
- 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