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.c
#include <stdio.h>
#include <stdint.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
gcc -o strings_example strings_example.c 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.c
// 编码后,添加以下代码:
FILE *f = fopen("encoded.bin", "wb");
fwrite(buffer, 1, message_length, f);
fclose(f);

替代方案:基于 Callback 的字符串

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

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

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

strings_callback_example.c
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include "strings.pb.h"
#include "pb_encode.h"
#include "pb_decode.h"

typedef struct {
    char* data;
    size_t size;
} dynamic_string_t;

// 字符串的编码 callback
bool string_encode_callback(pb_ostream_t *stream, const pb_field_t *field, void * const *arg) {
    const dynamic_string_t* str = (const dynamic_string_t*)*arg;
    
    if (!pb_encode_tag_for_field(stream, field))
        return false;
    
    return pb_encode_string(stream, (const pb_byte_t*)str->data, str->size);
}

// 字符串的解码 callback
bool string_decode_callback(pb_istream_t *stream, const pb_field_t *field, void **arg) {
    dynamic_string_t* str = (dynamic_string_t*)*arg;
    
    // 分配缓冲区
    size_t size = stream->bytes_left;
    str->data = (char*)malloc(size + 1);
    
    if (!pb_read(stream, (pb_byte_t*)str->data, size)) {
        free(str->data);
        str->data = NULL;
        return false;
    }
    
    str->data[size] = '\0'; // 添加 null 终止符
    str->size = size;
    return true;
}

int main() {
    uint8_t buffer[256];
    size_t message_length;
    
    dynamic_string_t name = {"NanoPB", 6};
    dynamic_string_t description = {"Protocol Buffers for embedded systems", 38};
    
    // --- 编码 ---
    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;
    dynamic_string_t decoded_name = {NULL, 0};
    dynamic_string_t decoded_description = {NULL, 0};
    
    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.data);
    printf("  description: %s\n", decoded_description.data);
    
    // 释放已分配的内存
    free(decoded_name.data);
    free(decoded_description.data);
    
    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

与 C++ 的区别

C 版本与 C++ 版本几乎相同,主要区别如下:

更多 NanoPB 文章


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