NanoPB:如何在 C++ 中处理 repeated 字段(数组)

另请参阅:C 版本:如何在 C 中处理 repeated 字段/数组

NanoPB 是一个面向嵌入式系统的代码体积优化的 Protocol Buffers 实现。本文介绍如何在 C++ 中使用 NanoPB 处理 repeated 字段(数组)。

Proto 定义

首先,创建一个包含 repeated 字段的 .proto 文件:

repeated.proto
syntax = "proto3";

package example;

message RepeatedMessage {
  repeated uint32 values = 1;
  repeated float temperatures = 2;
}

生成 NanoPB 代码

使用 .options 文件指定数组大小,然后生成 NanoPB 代码:

创建 repeated.options

repeated.options
example.RepeatedMessage.values max_count:10

然后生成:

generate_nanopb_repeated.sh
protoc --nanopb_out=. repeated.proto

这将生成 repeated.pb.hrepeated.pb.c

使用固定大小数组的 C++ 示例

下面是一个使用固定大小数组的完整 C++ 示例:

repeated_example.cpp
#include <stdio.h>
#include "repeated.pb.h"
#include "pb_encode.h"
#include "pb_decode.h"

int main() {
    // 编码消息的缓冲区
    uint8_t buffer[256];
    size_t message_length;
    
    // --- 编码 ---
    example_RepeatedMessage message = example_RepeatedMessage_init_zero;
    
    // 设置 repeated 字段的值
    message.values[0] = 10;
    message.values[1] = 20;
    message.values[2] = 30;
    message.values_count = 3;  // 重要:设置计数
    
    message.temperatures[0] = 20.5f;
    message.temperatures[1] = 21.0f;
    message.temperatures[2] = 21.5f;
    message.temperatures_count = 3;  // 重要:设置计数
    
    // 创建编码流
    pb_ostream_t ostream = pb_ostream_from_buffer(buffer, sizeof(buffer));
    
    // 编码消息
    if (!pb_encode(&ostream, example_RepeatedMessage_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_RepeatedMessage decoded = example_RepeatedMessage_init_zero;
    
    // 创建解码流
    pb_istream_t istream = pb_istream_from_buffer(buffer, message_length);
    
    // 解码消息
    if (!pb_decode(&istream, example_RepeatedMessage_fields, &decoded)) {
        printf("Decoding failed: %s\n", PB_GET_ERROR(&istream));
        return 1;
    }
    
    // 打印解码后的值
    printf("Decoded values:\n");
    printf("  values (%zu items): ", decoded.values_count);
    for (size_t i = 0; i < decoded.values_count; i++) {
        printf("%u ", decoded.values[i]);
    }
    printf("\n");
    
    printf("  temperatures (%zu items): ", decoded.temperatures_count);
    for (size_t i = 0; i < decoded.temperatures_count; i++) {
        printf("%.1f ", decoded.temperatures[i]);
    }
    printf("\n");
    
    return 0;
}

编译命令

使用 nanopb 编译该示例。NanoPB 通常通过将源文件直接包含到你的项目来使用:

compile_repeated_example.sh
g++ -o repeated_example repeated_example.cpp repeated.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_repeated.py
import repeated_pb2

# 读取二进制数据
with open('encoded.bin', 'rb') as f:
    data = f.read()

# 解码
msg = repeated_pb2.RepeatedMessage()
msg.ParseFromString(data)

print("Python decoded values:")
print(f"  values: {list(msg.values)}")
print(f"  temperatures: {list(msg.temperatures)}")

首先,编译 Python protobuf 定义:

compile_python_repeated.sh
protoc --python_out=. repeated.proto

然后修改 C++ 示例,将编码后的数据保存到文件:

save_encoded_repeated.cpp
// 编码后,添加以下代码:
FILE *f = fopen("encoded.bin", "wb");
fwrite(buffer, 1, message_length, f);
fclose(f);

替代方案:基于 Callback 的 repeated 字段

对于动态数组处理,你可以使用 Callback。创建 repeated_callback.options

repeated_callback.options
# 对动态数组使用 callback
msg.RepeatedMessage.values callback
msg.RepeatedMessage.temperatures callback

然后重新生成并使用以下方式:

repeated_callback_example.cpp
#include <stdio.h>
#include <vector>
#include "repeated.pb.h"
#include "pb_encode.h"
#include "pb_decode.h"

// uint32 数组的编码 callback
bool uint32_array_encode_callback(pb_ostream_t *stream, const pb_field_t *field, void * const *arg) {
    const std::vector<uint32_t>* arr = (const std::vector<uint32_t>*)*arg;
    
    for (uint32_t value : *arr) {
        if (!pb_encode_tag_for_field(stream, field))
            return false;
        
        if (!pb_encode_varint(stream, value))
            return false;
    }
    
    return true;
}

// uint32 数组的解码 callback
bool uint32_array_decode_callback(pb_istream_t *stream, const pb_field_t *field, void **arg) {
    std::vector<uint32_t>* arr = (std::vector<uint32_t>*)*arg;
    
    uint64_t value;
    if (!pb_decode_varint(stream, &value))
        return false;
    
    arr->push_back((uint32_t)value);
    return true;
}

// float 数组的编码 callback
bool float_array_encode_callback(pb_ostream_t *stream, const pb_field_t *field, void * const *arg) {
    const std::vector<float>* arr = (const std::vector<float>*)*arg;
    
    for (float value : *arr) {
        if (!pb_encode_tag_for_field(stream, field))
            return false;
        
        // 将 float 编码为 4 字节
        union { float f; uint32_t u; } u;
        u.f = value;
        if (!pb_encode_varint(stream, u.u))
            return false;
    }
    
    return true;
}

// float 数组的解码 callback
bool float_array_decode_callback(pb_istream_t *stream, const pb_field_t *field, void **arg) {
    std::vector<float>* arr = (std::vector<float>*)*arg;
    
    uint64_t value;
    if (!pb_decode_varint(stream, &value))
        return false;
    
    union { float f; uint32_t u; } u;
    u.u = (uint32_t)value;
    arr->push_back(u.f);
    return true;
}

int main() {
    uint8_t buffer[256];
    size_t message_length;
    
    std::vector<uint32_t> values = {10, 20, 30};
    std::vector<float> temperatures = {20.5f, 21.0f, 21.5f};
    
    // --- 编码 ---
    example_RepeatedMessage message = example_RepeatedMessage_init_zero;
    
    message.values.funcs.encode = uint32_array_encode_callback;
    message.values.arg = &values;
    
    message.temperatures.funcs.encode = float_array_encode_callback;
    message.temperatures.arg = &temperatures;
    
    pb_ostream_t ostream = pb_ostream_from_buffer(buffer, sizeof(buffer));
    
    if (!pb_encode(&ostream, example_RepeatedMessage_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_RepeatedMessage decoded = example_RepeatedMessage_init_zero;
    std::vector<uint32_t> decoded_values;
    std::vector<float> decoded_temperatures;
    
    decoded.values.funcs.decode = uint32_array_decode_callback;
    decoded.values.arg = &decoded_values;
    
    decoded.temperatures.funcs.decode = float_array_decode_callback;
    decoded.temperatures.arg = &decoded_temperatures;
    
    pb_istream_t istream = pb_istream_from_buffer(buffer, message_length);
    
    if (!pb_decode(&istream, example_RepeatedMessage_fields, &decoded)) {
        printf("Decoding failed: %s\n", PB_GET_ERROR(&istream));
        return 1;
    }
    
    printf("Decoded values:\n");
    printf("  values (%zu items): ", decoded_values.size());
    for (uint32_t value : decoded_values) {
        printf("%u ", value);
    }
    printf("\n");
    
    printf("  temperatures (%zu items): ", decoded_temperatures.size());
    for (float temp : decoded_temperatures) {
        printf("%.1f ", temp);
    }
    printf("\n");
    
    return 0;
}

要点

何时使用哪种方式

预期输出

repeated_expected_output.txt
Encoded 15 bytes
Encoded data: 08 0a 08 14 08 1e 15 00 00 a4 41 15 00 00 a8 41 15 00 00 ac 41 
Decoded values:
  values (3 items): 10 20 30 
  temperatures (3 items): 20.5 21.0 21.5 

更多 NanoPB 文章


Check out similar posts by category: Embedded, C/C++, Protocol Buffers