NanoPB:如何在 C 中处理枚举
另请参阅:C++ 版本:如何在 C++ 中处理枚举
NanoPB 是一个面向嵌入式系统的代码体积优化的 Protocol Buffers 实现。本文介绍如何在 C 中使用 NanoPB 处理枚举类型。
Proto 定义
首先,创建一个包含枚举的 .proto 文件:
enums.proto
syntax = "proto3";
package example;
enum Status {
UNKNOWN = 0;
OK = 1;
ERROR = 2;
BUSY = 3;
}
message EnumMessage {
Status status = 1;
}生成 NanoPB 代码
生成 NanoPB 代码:
generate_nanopb_enums.sh
protoc --nanopb_out=. enums.proto这将生成 enums.pb.h 和 enums.pb.c。
C 示例
以下是一个处理枚举的完整 C 示例:
enums_example.c
#include <stdio.h>
#include <stdint.h>
#include "enums.pb.h"
#include "pb_encode.h"
#include "pb_decode.h"
// 将枚举转换为字符串的辅助函数
const char* status_to_string(example_Status status) {
switch (status) {
case example_Status_UNKNOWN: return "UNKNOWN";
case example_Status_OK: return "OK";
case example_Status_ERROR: return "ERROR";
case example_Status_BUSY: return "BUSY";
default: return "INVALID";
}
}
int main() {
// 编码消息的缓冲区
uint8_t buffer[64];
size_t message_length;
// --- 编码 ---
example_EnumMessage message = example_EnumMessage_init_zero;
// 设置枚举值
message.status = example_Status_OK;
// 创建编码流
pb_ostream_t ostream = pb_ostream_from_buffer(buffer, sizeof(buffer));
// 编码消息
if (!pb_encode(&ostream, example_EnumMessage_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_EnumMessage decoded = example_EnumMessage_init_zero;
// 创建解码流
pb_istream_t istream = pb_istream_from_buffer(buffer, message_length);
// 解码消息
if (!pb_decode(&istream, example_EnumMessage_fields, &decoded)) {
printf("Decoding failed: %s\n", PB_GET_ERROR(&istream));
return 1;
}
// 打印解码后的值
printf("Decoded value:\n");
printf(" status: %s (enum value: %d)\n",
status_to_string(decoded.status), (int)decoded.status);
return 0;
}编译命令
使用 nanopb 编译示例。NanoPB 通常通过将源文件直接包含到项目中来使用:
compile_enums_example.sh
gcc -o enums_example enums_example.c enums.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_enums.py
import enums_pb2
# 读取二进制数据
with open('encoded.bin', 'rb') as f:
data = f.read()
# 解码
msg = enums_pb2.EnumMessage()
msg.ParseFromString(data)
print("Python decoded values:")
print(f" status: {enums_pb2.Status.Name(msg.status)}")首先,编译 Python protobuf 定义:
compile_python_enums.sh
protoc --python_out=. enums.proto然后修改 C 示例,将编码后的数据保存到文件:
save_encoded_enums.c
// 编码后,添加以下代码:
FILE *f = fopen("encoded.bin", "wb");
fwrite(buffer, 1, message_length, f);
fclose(f);在 switch 语句中使用枚举的示例
以下示例展示如何在 switch 语句中使用枚举:
enums_switch_example.c
#include <stdio.h>
#include <stdint.h>
#include "enums.pb.h"
#include "pb_encode.h"
#include "pb_decode.h"
void handle_status(example_Status status) {
printf("Handling status: ");
switch (status) {
case example_Status_UNKNOWN:
printf("UNKNOWN - Default state\n");
break;
case example_Status_OK:
printf("OK - Operation successful\n");
break;
case example_Status_ERROR:
printf("ERROR - Operation failed\n");
break;
case example_Status_BUSY:
printf("BUSY - System busy\n");
break;
default:
printf("INVALID - Unknown enum value\n");
break;
}
}
int main() {
uint8_t buffer[64];
size_t message_length;
// 测试所有枚举值
example_Status test_values[] = {
example_Status_UNKNOWN,
example_Status_OK,
example_Status_ERROR,
example_Status_BUSY
};
for (size_t i = 0; i < 4; i++) {
example_EnumMessage message = example_EnumMessage_init_zero;
message.status = test_values[i];
pb_ostream_t ostream = pb_ostream_from_buffer(buffer, sizeof(buffer));
if (!pb_encode(&ostream, example_EnumMessage_fields, &message)) {
printf("Encoding failed: %s\n", PB_GET_ERROR(&ostream));
return 1;
}
message_length = ostream.bytes_written;
example_EnumMessage decoded = example_EnumMessage_init_zero;
pb_istream_t istream = pb_istream_from_buffer(buffer, message_length);
if (!pb_decode(&istream, example_EnumMessage_fields, &decoded)) {
printf("Decoding failed: %s\n", PB_GET_ERROR(&istream));
return 1;
}
handle_status(decoded.status);
}
return 0;
}要点
- 枚举定义:在
.proto文件中定义枚举并指定显式值 - 生成的类型:NanoPB 以
package_EnumName命名方式生成枚举类型 - 编码:直接将枚举值赋给字段
- 解码:枚举值会自动解码
- 默认值:第一个枚举值(通常为 0)是默认值
- switch 语句:枚举在 switch 语句中自然适用
- 类型安全:枚举相比原始整数提供类型安全
- 未知值:无效的枚举值可能被解码为其数值
何时使用枚举
- 当你有一组固定的可能值时
- 当你想为状态或模式字段提供类型安全时
- 当你想让代码自文档化时
- 当你需要区分不同的操作模式时
- 当你想在消息中编码语义含义时
预期输出
enums_expected_output.txt
Encoded 2 bytes
Encoded data: 08 01
Decoded value:
status: OK (enum value: 1)预期输出(switch 示例)
enums_switch_expected_output.txt
Handling status: UNKNOWN - Default state
Handling status: OK - Operation successful
Handling status: ERROR - Operation failed
Handling status: BUSY - System busy与 C++ 的区别
C 版本与 C++ 版本几乎相同:
- 枚举在 C 和 C++ 中的工作方式相同
- 在 C 中对 printf 格式说明符使用显式类型转换
- 枚举处理不需要 C++ 特有的功能
- 两种语言生成的代码完全相同
更多 NanoPB 文章
- C++ 中的基本标量类型
- C 中的基本标量类型
- C++ 中的字符串类型
- C 中的字符串类型
- C++ 中的 bytes 类型
- C 中的 bytes 类型
- C++ 中的可选字段
- C 中的可选字段
- C++ 中的 repeated 字段/数组
- C 中的 repeated 字段/数组
- 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