NanoPB:如何在 C++ 中处理字符串类型

另请参阅:C 版本:如何在 C 中处理字符串类型

NanoPB 是一个面向嵌入式系统的代码体积优化的 Protocol Buffers 实现。本文介绍如何在 C++ 中使用 NanoPB 处理字符串类型。

Proto 定义

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

strings.proto
syntax = "proto3";

package example;

message StringMessage {
  string name = 1;
  string description = 2;
}

生成 NanoPB 代码

使用 .options 文件指定字符串缓冲区大小来生成 NanoPB 代码:

创建 strings.options

strings.options
example.StringMessage.name max_size:64
example.StringMessage.description max_size:256

然后生成:

generate_nanopb_strings.sh
protoc --nanopb_out=. strings.proto

这将生成 strings.pb.hstrings.pb.c

使用固定大小缓冲区的 C++ 示例

以下是一个使用固定大小缓冲区的完整 C++ 示例:

strings_example.cpp
#include <stdio.h>
#include <string.h>
#include "strings.pb.h"
#include "pb_encode.h"
#include "pb_decode.h"

int main() {
    // 编码消息的缓冲区
    uint8_t buffer[256];
    size_t message_length;
    
    // --- 编码 ---
    example_StringMessage message = example_StringMessage_init_zero;
    
    // 设置字符串值(必须适合缓冲区大小)
    const char* name = "NanoPB";
    const char* description = "Protocol Buffers for embedded systems";
    
    strncpy(message.name, name, sizeof(message.name) - 1);
    strncpy(message.description, description, sizeof(message.description) - 1);
    
    // 创建编码流
    pb_ostream_t ostream = pb_ostream_from_buffer(buffer, sizeof(buffer));
    
    // 编码消息
    if (!pb_encode(&ostream, example_StringMessage_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_StringMessage decoded = example_StringMessage_init_zero;
    
    // 创建解码流
    pb_istream_t istream = pb_istream_from_buffer(buffer, message_length);
    
    // 解码消息
    if (!pb_decode(&istream, example_StringMessage_fields, &decoded)) {
        printf("Decoding failed: %s\n", PB_GET_ERROR(&istream));
        return 1;
    }
    
    // 打印解码后的值
    printf("Decoded values:\n");
    printf("  name: %s\n", decoded.name);
    printf("  description: %s\n", decoded.description);
    
    return 0;
}

编译命令

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

compile_strings_example.sh
g++ -o strings_example strings_example.cpp strings.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_strings.py
import strings_pb2

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

# 解码
msg = strings_pb2.StringMessage()
msg.ParseFromString(data)

print("Python decoded values:")
print(f"  name: {msg.name}")
print(f"  description: {msg.description}")

首先,编译 Python protobuf 定义:

compile_python_strings.sh
protoc --python_out=. strings.proto

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

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

替代方案:基于回调的字符串处理

对于动态字符串处理,可以使用回调。创建 strings_callback.options

strings_callback.options
# 对动态字符串使用回调
msg.StringMessage.name callback
msg.StringMessage.description callback

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

strings_callback_example.cpp
#include <stdio.h>
#include <string>
#include "strings.pb.h"
#include "pb_encode.h"
#include "pb_decode.h"

// 字符串的编码回调
bool string_encode_callback(pb_ostream_t *stream, const pb_field_t *field, void * const *arg) {
    const std::string* str = (const std::string*)*arg;
    
    if (!pb_encode_tag_for_field(stream, field))
        return false;
    
    return pb_encode_string(stream, (const pb_byte_t*)str->c_str(), str->size());
}

// 字符串的解码回调
bool string_decode_callback(pb_istream_t *stream, const pb_field_t *field, void **arg) {
    std::string* str = (std::string*)*arg;
    
    // 分配缓冲区
    size_t size = stream->bytes_left;
    char* buf = new char[size];
    
    if (!pb_read(stream, (pb_byte_t*)buf, size)) {
        delete[] buf;
        return false;
    }
    
    str->assign(buf, size);
    delete[] buf;
    return true;
}

int main() {
    uint8_t buffer[256];
    size_t message_length;
    
    std::string name = "NanoPB";
    std::string description = "Protocol Buffers for embedded systems";
    
    // --- 编码 ---
    example_StringMessage message = example_StringMessage_init_zero;
    
    message.name.funcs.encode = string_encode_callback;
    message.name.arg = &name;
    message.description.funcs.encode = string_encode_callback;
    message.description.arg = &description;
    
    pb_ostream_t ostream = pb_ostream_from_buffer(buffer, sizeof(buffer));
    
    if (!pb_encode(&ostream, example_StringMessage_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_StringMessage decoded = example_StringMessage_init_zero;
    std::string decoded_name, decoded_description;
    
    decoded.name.funcs.decode = string_decode_callback;
    decoded.name.arg = &decoded_name;
    decoded.description.funcs.decode = string_decode_callback;
    decoded.description.arg = &decoded_description;
    
    pb_istream_t istream = pb_istream_from_buffer(buffer, message_length);
    
    if (!pb_decode(&istream, example_StringMessage_fields, &decoded)) {
        printf("Decoding failed: %s\n", PB_GET_ERROR(&istream));
        return 1;
    }
    
    printf("Decoded values:\n");
    printf("  name: %s\n", decoded_name.c_str());
    printf("  description: %s\n", decoded_description.c_str());
    
    return 0;
}

要点

何时使用哪种方法

预期输出

strings_expected_output.txt
Encoded 38 bytes
Encoded data: 0a 06 4e 61 6e 6f 50 42 12 1e 50 72 6f 74 6f 63 6f 6c 20 42 75 66 66 65 72 73 20 66 6f 72 20 65 6d 62 65 64 64 65 64 20 73 79 73 74 65 6d 73 
Decoded values:
  name: NanoPB
  description: Protocol Buffers for embedded systems

更多 NanoPB 文章


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