NanoPB: How to handle basic scalar types in C++
See also: C version: How to handle basic scalar types in C
NanoPB is a code-size optimized Protocol Buffers implementation for embedded systems. This post shows how to handle basic scalar types (integers, floats, booleans) in C++ with NanoPB.
Proto definition
First, create a simple .proto file with basic scalar types:
syntax = "proto3";
package example;
message ScalarMessage {
uint32 uint32_value = 1;
uint64 uint64_value = 2;
int32 int32_value = 3;
int64 int64_value = 4;
float float_value = 5;
bool bool_value = 6;
}Generate NanoPB code
Generate the C++ NanoPB code using the nanopb generator:
protoc --nanopb_out=. scalars.protoThis will generate scalars.pb.h and scalars.pb.c.
C++ example
Here’s a complete C++ example that encodes and decodes the message:
#include <stdio.h>
#include <string.h>
#include "scalars.pb.h"
#include "pb_encode.h"
#include "pb_decode.h"
int main() {
// Buffer for encoded message
uint8_t buffer[128];
size_t message_length;
// --- ENCODING ---
example_ScalarMessage message = example_ScalarMessage_init_zero;
// Set field values
message.uint32_value = 42;
message.uint64_value = 1234567890ULL;
message.int32_value = -100;
message.int64_value = -9876543210LL;
message.float_value = 3.14159f;
message.bool_value = true;
// Create stream for encoding
pb_ostream_t ostream = pb_ostream_from_buffer(buffer, sizeof(buffer));
// Encode the message
if (!pb_encode(&ostream, example_ScalarMessage_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_ScalarMessage decoded = example_ScalarMessage_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_ScalarMessage_fields, &decoded)) {
printf("Decoding failed: %s\n", PB_GET_ERROR(&istream));
return 1;
}
// Print decoded values
printf("Decoded values:\n");
printf(" uint32_value: %u\n", decoded.uint32_value);
printf(" uint64_value: %llu\n", (unsigned long long)decoded.uint64_value);
printf(" int32_value: %d\n", decoded.int32_value);
printf(" int64_value: %lld\n", (long long)decoded.int64_value);
printf(" float_value: %f\n", decoded.float_value);
printf(" bool_value: %s\n", decoded.bool_value ? "true" : "false");
return 0;
}Compile command
Compile the example with nanopb. NanoPB is typically used by including the source files directly in your project:
g++ -o scalars_example scalars_example.cpp scalars.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 scalars_pb2
# Read the binary data
with open('encoded.bin', 'rb') as f:
data = f.read()
# Decode
msg = scalars_pb2.ScalarMessage()
msg.ParseFromString(data)
print("Python decoded values:")
print(f" uint32_value: {msg.uint32_value}")
print(f" uint64_value: {msg.uint64_value}")
print(f" int32_value: {msg.int32_value}")
print(f" int64_value: {msg.int64_value}")
print(f" float_value: {msg.float_value}")
print(f" bool_value: {msg.bool_value}")First, compile the Python protobuf definitions:
protoc --python_out=. scalars.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);Key points
- Use
*_init_zeroto initialize messages with default values pb_ostream_from_buffercreates an output stream for encodingpb_istream_from_buffercreates an input stream for decodingpb_encodeandpb_decodehandle the actual encoding/decoding- Check return values and use
PB_GET_ERRORfor error handling
Expected output
Encoded 28 bytes
Encoded data: 08 2a 10 d2 95 89 04 18 9c ff ff ff ff ff ff ff 01 20 c6 ef be ad de 05 2d 15 49 0e 40 30 01
Decoded values:
uint32_value: 42
uint64_value: 1234567890
int32_value: -100
int64_value: -9876543210
float_value: 3.141590
bool_value: trueMore NanoPB posts
- 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++
- 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