NanoPB: How to handle enums in C++
See also: C version: How to handle enums in C
NanoPB is a code-size optimized Protocol Buffers implementation for embedded systems. This post shows how to handle enum types in C++ with NanoPB.
Proto definition
First, create a .proto file with enums:
syntax = "proto3";
package example;
enum Status {
UNKNOWN = 0;
OK = 1;
ERROR = 2;
BUSY = 3;
}
message EnumMessage {
Status status = 1;
}Generate NanoPB code
Generate the NanoPB code:
protoc --nanopb_out=. enums.protoThis will generate enums.pb.h and enums.pb.c.
C++ example
Here’s a complete C++ example handling enums:
#include <stdio.h>
#include "enums.pb.h"
#include "pb_encode.h"
#include "pb_decode.h"
// Helper function to convert enum to string
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() {
// Buffer for encoded message
uint8_t buffer[64];
size_t message_length;
// --- ENCODING ---
example_EnumMessage message = example_EnumMessage_init_zero;
// Set enum value
message.status = example_Status_OK;
// Create stream for encoding
pb_ostream_t ostream = pb_ostream_from_buffer(buffer, sizeof(buffer));
// Encode the message
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);
// Print hex dump of encoded data
printf("Encoded data: ");
for (size_t i = 0; i < message_length; i++) {
printf("%02x ", buffer[i]);
}
printf("\n");
// --- DECODING ---
example_EnumMessage decoded = example_EnumMessage_init_zero;
// Create stream for decoding
pb_istream_t istream = pb_istream_from_buffer(buffer, message_length);
// Decode the message
if (!pb_decode(&istream, example_EnumMessage_fields, &decoded)) {
printf("Decoding failed: %s\n", PB_GET_ERROR(&istream));
return 1;
}
// Print decoded value
printf("Decoded value:\n");
printf(" status: %s (enum value: %d)\n",
status_to_string(decoded.status), decoded.status);
return 0;
}Compile command
Compile the example with nanopb. NanoPB is typically used by including the source files directly in your project:
g++ -o enums_example enums_example.cpp enums.pb.c pb_common.c pb_encode.c pb_decode.c -I.Note: NanoPB source files (pb_common.c, pb_encode.c, pb_decode.c) need to be compiled directly with your project. You can obtain these from the NanoPB GitHub repository.
Python test script
To verify the encoding, you can use Python’s protobuf library:
import enums_pb2
# Read the binary data
with open('encoded.bin', 'rb') as f:
data = f.read()
# Decode
msg = enums_pb2.EnumMessage()
msg.ParseFromString(data)
print("Python decoded values:")
print(f" status: {enums_pb2.Status.Name(msg.status)}")First, compile the Python protobuf definitions:
protoc --python_out=. enums.protoThen modify the C++ example to save the encoded data to a file:
// After encoding, add this:
FILE *f = fopen("encoded.bin", "wb");
fwrite(buffer, 1, message_length, f);
fclose(f);Example with enum in switch statement
Here’s an example showing how to use enums in switch statements:
#include <stdio.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;
// Test all enum values
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;
}Key points
- Enum definition: Define enums in
.protofile with explicit values - Generated types: NanoPB generates enum types with
package_EnumNamenaming - Encoding: Assign enum value directly to field
- Decoding: Enum values are decoded automatically
- Default values: First enum value (typically 0) is the default
- Switch statements: Enums work naturally in switch statements
- Type safety: Enums provide type safety over raw integers
- Unknown values: Invalid enum values may be decoded as their numeric value
When to use enums
- When you have a fixed set of possible values
- When you want type safety for state or mode fields
- When you want self-documenting code
- When you need to distinguish between different operation modes
- When you want to encode semantic meaning in messages
Expected output
Encoded 2 bytes
Encoded data: 08 01
Decoded value:
status: OK (enum value: 1)Expected output (switch example)
Handling status: UNKNOWN - Default state
Handling status: OK - Operation successful
Handling status: ERROR - Operation failed
Handling status: BUSY - System busyMore NanoPB posts
- Basic scalar types in C++
- Basic scalar types in C
- String types in C++
- String types in C
- Bytes types in C++
- Bytes types in C
- Optional fields in C++
- Optional fields in C
- Repeated fields/arrays in C++
- Repeated fields/arrays in C
- Enums in C
- Nested messages in C++
- Nested messages in C
- Oneof/union types in C++
- Oneof/union types in C
- Custom array converters in C++
- Custom array converters in C