NanoPB: How to handle repeated fields (arrays) in C++

See also: C version: How to handle repeated fields/arrays in C

NanoPB is a code-size optimized Protocol Buffers implementation for embedded systems. This post shows how to handle repeated fields (arrays) in C++ with NanoPB.

Proto definition

First, create a .proto file with repeated fields:

repeated.proto
syntax = "proto3";

package example;

message RepeatedMessage {
  repeated uint32 values = 1;
  repeated float temperatures = 2;
}

Generate NanoPB code

Generate the NanoPB code with a .options file to specify array sizes:

Create repeated.options:

example.txt
example.RepeatedMessage.values max_count:10

Then generate:

example.sh
protoc --nanopb_out=. repeated.proto

This will generate repeated.pb.h and repeated.pb.c.

C++ example with fixed-size arrays

Here’s a complete C++ example using fixed-size arrays:

repeated_example.cpp
#include <stdio.h>
#include "repeated.pb.h"
#include "pb_encode.h"
#include "pb_decode.h"

int main() {
    // Buffer for encoded message
    uint8_t buffer[256];
    size_t message_length;
    
    // --- ENCODING ---
    example_RepeatedMessage message = example_RepeatedMessage_init_zero;
    
    // Set repeated field values
    message.values[0] = 10;
    message.values[1] = 20;
    message.values[2] = 30;
    message.values_count = 3;  // Important: set count
    
    message.temperatures[0] = 20.5f;
    message.temperatures[1] = 21.0f;
    message.temperatures[2] = 21.5f;
    message.temperatures_count = 3;  // Important: set count
    
    // Create stream for encoding
    pb_ostream_t ostream = pb_ostream_from_buffer(buffer, sizeof(buffer));
    
    // Encode the message
    if (!pb_encode(&ostream, example_RepeatedMessage_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_RepeatedMessage decoded = example_RepeatedMessage_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_RepeatedMessage_fields, &decoded)) {
        printf("Decoding failed: %s\n", PB_GET_ERROR(&istream));
        return 1;
    }
    
    // Print decoded values
    printf("Decoded values:\n");
    printf("  values (%zu items): ", decoded.values_count);
    for (size_t i = 0; i < decoded.values_count; i++) {
        printf("%u ", decoded.values[i]);
    }
    printf("\n");
    
    printf("  temperatures (%zu items): ", decoded.temperatures_count);
    for (size_t i = 0; i < decoded.temperatures_count; i++) {
        printf("%.1f ", decoded.temperatures[i]);
    }
    printf("\n");
    
    return 0;
}

Compile command

Compile the example with nanopb. NanoPB is typically used by including the source files directly in your project:

example.sh
g++ -o repeated_example repeated_example.cpp repeated.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:

test_repeated.py
import repeated_pb2

# Read the binary data
with open('encoded.bin', 'rb') as f:
    data = f.read()

# Decode
msg = repeated_pb2.RepeatedMessage()
msg.ParseFromString(data)

print("Python decoded values:")
print(f"  values: {list(msg.values)}")
print(f"  temperatures: {list(msg.temperatures)}")

First, compile the Python protobuf definitions:

example.sh
protoc --python_out=. repeated.proto

Then modify the C++ example to save the encoded data to a file:

example.cpp
// After encoding, add this:
FILE *f = fopen("encoded.bin", "wb");
fwrite(buffer, 1, message_length, f);
fclose(f);

Alternative: Callback-based repeated fields

For dynamic array handling, you can use callbacks. Create repeated_callback.options:

example.txt
# Use callback for dynamic arrays
msg.RepeatedMessage.values callback
msg.RepeatedMessage.temperatures callback

Then regenerate and use this approach:

repeated_callback_example.cpp
#include <stdio.h>
#include <vector>
#include "repeated.pb.h"
#include "pb_encode.h"
#include "pb_decode.h"

// Encoder callback for uint32 array
bool uint32_array_encode_callback(pb_ostream_t *stream, const pb_field_t *field, void * const *arg) {
    const std::vector<uint32_t>* arr = (const std::vector<uint32_t>*)*arg;
    
    for (uint32_t value : *arr) {
        if (!pb_encode_tag_for_field(stream, field))
            return false;
        
        if (!pb_encode_varint(stream, value))
            return false;
    }
    
    return true;
}

// Decoder callback for uint32 array
bool uint32_array_decode_callback(pb_istream_t *stream, const pb_field_t *field, void **arg) {
    std::vector<uint32_t>* arr = (std::vector<uint32_t>*)*arg;
    
    uint64_t value;
    if (!pb_decode_varint(stream, &value))
        return false;
    
    arr->push_back((uint32_t)value);
    return true;
}

// Encoder callback for float array
bool float_array_encode_callback(pb_ostream_t *stream, const pb_field_t *field, void * const *arg) {
    const std::vector<float>* arr = (const std::vector<float>*)*arg;
    
    for (float value : *arr) {
        if (!pb_encode_tag_for_field(stream, field))
            return false;
        
        // Encode float as 4 bytes
        union { float f; uint32_t u; } u;
        u.f = value;
        if (!pb_encode_varint(stream, u.u))
            return false;
    }
    
    return true;
}

// Decoder callback for float array
bool float_array_decode_callback(pb_istream_t *stream, const pb_field_t *field, void **arg) {
    std::vector<float>* arr = (std::vector<float>*)*arg;
    
    uint64_t value;
    if (!pb_decode_varint(stream, &value))
        return false;
    
    union { float f; uint32_t u; } u;
    u.u = (uint32_t)value;
    arr->push_back(u.f);
    return true;
}

int main() {
    uint8_t buffer[256];
    size_t message_length;
    
    std::vector<uint32_t> values = {10, 20, 30};
    std::vector<float> temperatures = {20.5f, 21.0f, 21.5f};
    
    // --- ENCODING ---
    example_RepeatedMessage message = example_RepeatedMessage_init_zero;
    
    message.values.funcs.encode = uint32_array_encode_callback;
    message.values.arg = &values;
    
    message.temperatures.funcs.encode = float_array_encode_callback;
    message.temperatures.arg = &temperatures;
    
    pb_ostream_t ostream = pb_ostream_from_buffer(buffer, sizeof(buffer));
    
    if (!pb_encode(&ostream, example_RepeatedMessage_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);
    
    // --- DECODING ---
    example_RepeatedMessage decoded = example_RepeatedMessage_init_zero;
    std::vector<uint32_t> decoded_values;
    std::vector<float> decoded_temperatures;
    
    decoded.values.funcs.decode = uint32_array_decode_callback;
    decoded.values.arg = &decoded_values;
    
    decoded.temperatures.funcs.decode = float_array_decode_callback;
    decoded.temperatures.arg = &decoded_temperatures;
    
    pb_istream_t istream = pb_istream_from_buffer(buffer, message_length);
    
    if (!pb_decode(&istream, example_RepeatedMessage_fields, &decoded)) {
        printf("Decoding failed: %s\n", PB_GET_ERROR(&istream));
        return 1;
    }
    
    printf("Decoded values:\n");
    printf("  values (%zu items): ", decoded_values.size());
    for (uint32_t value : decoded_values) {
        printf("%u ", value);
    }
    printf("\n");
    
    printf("  temperatures (%zu items): ", decoded_temperatures.size());
    for (float temp : decoded_temperatures) {
        printf("%.1f ", temp);
    }
    printf("\n");
    
    return 0;
}

Key points

When to use which approach

Expected output

example.txt
Encoded 15 bytes
Encoded data: 08 0a 08 14 08 1e 15 00 00 a4 41 15 00 00 a8 41 15 00 00 ac 41 
Decoded values:
  values (3 items): 10 20 30 
  temperatures (3 items): 20.5 21.0 21.5 

More NanoPB posts


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