NanoPB:如何在 C++ 中处理 bytes 类型
NanoPB 是一个面向嵌入式系统的代码体积优化的 Protocol Buffers 实现。本文介绍如何在 C++ 中使用 NanoPB 处理 bytes 类型。
Proto 定义
首先,创建一个包含 bytes 字段的 .proto 文件:
bytes.proto
syntax = "proto3";
package example;
message BytesMessage {
bytes data = 1;
bytes signature = 2;
}生成 NanoPB 代码
使用 .options 文件指定 bytes 缓冲区大小来生成 NanoPB 代码:
创建 bytes.options:
bytes.options
example.BytesMessage.data max_size:32
example.BytesMessage.signature max_size:16然后生成:
generate_nanopb_bytes.sh
protoc --nanopb_out=. bytes.proto这将生成 bytes.pb.h 和 bytes.pb.c。
使用固定大小缓冲区的 C++ 示例
以下是一个使用固定大小缓冲区的完整 C++ 示例:
bytes_example.cpp
#include <stdio.h>
#include <string.h>
#include "bytes.pb.h"
#include "pb_encode.h"
#include "pb_decode.h"
int main() {
// 编码消息的缓冲区
uint8_t buffer[256];
size_t message_length;
// --- 编码 ---
example_BytesMessage message = example_BytesMessage_init_zero;
// 设置 bytes 数据
const uint8_t data[] = {0x01, 0x02, 0x03, 0x04, 0x05};
const uint8_t signature[] = {0xAA, 0xBB, 0xCC, 0xDD};
message.data.size = sizeof(data);
memcpy(message.data.bytes, data, sizeof(data));
message.signature.size = sizeof(signature);
memcpy(message.signature.bytes, signature, sizeof(signature));
// 创建编码流
pb_ostream_t ostream = pb_ostream_from_buffer(buffer, sizeof(buffer));
// 编码消息
if (!pb_encode(&ostream, example_BytesMessage_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_BytesMessage decoded = example_BytesMessage_init_zero;
// 创建解码流
pb_istream_t istream = pb_istream_from_buffer(buffer, message_length);
// 解码消息
if (!pb_decode(&istream, example_BytesMessage_fields, &decoded)) {
printf("Decoding failed: %s\n", PB_GET_ERROR(&istream));
return 1;
}
// 打印解码后的值
printf("Decoded values:\n");
printf(" data: ");
for (size_t i = 0; i < decoded.data.size; i++) {
printf("%02x ", decoded.data.bytes[i]);
}
printf("\n");
printf(" signature: ");
for (size_t i = 0; i < decoded.signature.size; i++) {
printf("%02x ", decoded.signature.bytes[i]);
}
printf("\n");
return 0;
}编译命令
使用 nanopb 编译示例。NanoPB 通常通过将源文件直接包含到项目中来使用:
compile_bytes_example.sh
g++ -o bytes_example bytes_example.cpp bytes.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_bytes.py
import bytes_pb2
# 读取二进制数据
with open('encoded.bin', 'rb') as f:
data = f.read()
# 解码
msg = bytes_pb2.BytesMessage()
msg.ParseFromString(data)
print("Python decoded values:")
print(f" data: {msg.data.hex()}")
print(f" signature: {msg.signature.hex()}")首先,编译 Python protobuf 定义:
compile_python_bytes.sh
protoc --python_out=. bytes.proto然后修改 C++ 示例,将编码后的数据保存到文件:
save_encoded_bytes.cpp
// 编码后,添加以下代码:
FILE *f = fopen("encoded.bin", "wb");
fwrite(buffer, 1, message_length, f);
fclose(f);替代方案:基于回调的 bytes 处理
对于动态 bytes 处理,可以使用回调。创建 bytes_callback.options:
bytes_callback.options
# 对动态 bytes 使用回调
msg.BytesMessage.data callback
msg.BytesMessage.signature callback然后重新生成并使用以下方法:
bytes_callback_example.cpp
#include <stdio.h>
#include <vector>
#include "bytes.pb.h"
#include "pb_encode.h"
#include "pb_decode.h"
// bytes 的编码回调
bool bytes_encode_callback(pb_ostream_t *stream, const pb_field_t *field, void * const *arg) {
const std::vector<uint8_t>* data = (const std::vector<uint8_t>*)*arg;
if (!pb_encode_tag_for_field(stream, field))
return false;
return pb_encode_string(stream, data->data(), data->size());
}
// bytes 的解码回调
bool bytes_decode_callback(pb_istream_t *stream, const pb_field_t *field, void **arg) {
std::vector<uint8_t>* data = (std::vector<uint8_t>*)*arg;
// 调整 vector 大小以容纳数据
size_t size = stream->bytes_left;
data->resize(size);
// 将数据读入 vector
return pb_read(stream, data->data(), size);
}
int main() {
uint8_t buffer[256];
size_t message_length;
std::vector<uint8_t> data = {0x01, 0x02, 0x03, 0x04, 0x05};
std::vector<uint8_t> signature = {0xAA, 0xBB, 0xCC, 0xDD};
// --- 编码 ---
example_BytesMessage message = example_BytesMessage_init_zero;
message.data.funcs.encode = bytes_encode_callback;
message.data.arg = &data;
message.signature.funcs.encode = bytes_encode_callback;
message.signature.arg = &signature;
pb_ostream_t ostream = pb_ostream_from_buffer(buffer, sizeof(buffer));
if (!pb_encode(&ostream, example_BytesMessage_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);
// --- 解码 ---
example_BytesMessage decoded = example_BytesMessage_init_zero;
std::vector<uint8_t> decoded_data, decoded_signature;
decoded.data.funcs.decode = bytes_decode_callback;
decoded.data.arg = &decoded_data;
decoded.signature.funcs.decode = bytes_decode_callback;
decoded.signature.arg = &decoded_signature;
pb_istream_t istream = pb_istream_from_buffer(buffer, message_length);
if (!pb_decode(&istream, example_BytesMessage_fields, &decoded)) {
printf("Decoding failed: %s\n", PB_GET_ERROR(&istream));
return 1;
}
printf("Decoded values:\n");
printf(" data: ");
for (uint8_t byte : decoded_data) {
printf("%02x ", byte);
}
printf("\n");
printf(" signature: ");
for (uint8_t byte : decoded_signature) {
printf("%02x ", byte);
}
printf("\n");
return 0;
}要点
- 固定大小缓冲区:在 .options 文件中使用
max_size实现简单的静态分配 - 基于回调:在 .options 中使用
callback实现动态 bytes 处理 - 固定大小:设置
*_size字段并使用memcpy复制 bytes - 基于回调:实现编码/解码回调以实现动态分配
- bytes 类似于字符串,但包含原始二进制数据(无 null 终止符)
- 在 C++ 中使用
std::vector<uint8_t>处理动态 bytes - 始终检查缓冲区大小以防止溢出
何时使用哪种方法
- 固定大小缓冲区:当你知道最大 bytes 大小且希望代码简单时
- 基于回调:当 bytes 大小可变或需要动态内存分配时
预期输出
bytes_expected_output.txt
Encoded 14 bytes
Encoded data: 0a 05 01 02 03 04 05 12 04 aa bb cc dd
Decoded values:
data: 01 02 03 04 05
signature: aa bb cc dd bytes 的使用场景
- 二进制数据(图像、音频等)
- 加密签名
- 原始传感器数据
- 自定义二进制协议
- 任何不应被解释为文本的数据
更多 NanoPB 文章
- C++ 中的基本标量类型
- C 中的基本标量类型
- C++ 中的字符串类型
- C 中的字符串类型
- 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