NanoPB: C++ でオプショナルフィールドを扱う方法

関連記事: C 版: C でオプショナルフィールドを扱う方法

NanoPB は組み込みシステム向けにコードサイズを最適化した Protocol Buffers 実装です。この記事では、NanoPB で C++ のオプショナルフィールド(proto3 optional)を扱う方法を説明します。

Proto 定義

まず、オプショナルフィールドを持つ .proto ファイルを作成します。

optional.proto
syntax = "proto3";

package example;

message OptionalMessage {
  optional uint32 id = 1;
  optional string name = 2;
  optional float temperature = 3;
  bool active = 4;  // 通常(非オプショナル)フィールド
}

NanoPB コードの生成

文字列バッファサイズを指定する .options ファイルを使って NanoPB コードを生成します。

optional.options を作成します。

optional.options
example.OptionalMessage.name max_size:64

次に生成します。

generate_nanopb_optional.sh
protoc --nanopb_out=. optional.proto

これにより optional.pb.h と optional.pb.c が生成されます。

C++ の例

オプショナルフィールドを扱う完全な C++ の例を示します。

optional_example.cpp
#include <stdio.h>
#include <string.h>
#include "optional.pb.h"
#include "pb_encode.h"
#include "pb_decode.h"

int main() {
    // エンコードされたメッセージ用バッファ
    uint8_t buffer[256];
    size_t message_length;
    
    // --- エンコード ---
    example_OptionalMessage message = example_OptionalMessage_init_zero;
    
    // オプショナルフィールドを設定
    message.id = 42;
    message.has_id = true;  // 重要: has_* フラグを設定
    
    strncpy(message.name, "Sensor1", sizeof(message.name) - 1);
    message.has_name = true;  // 重要: has_* フラグを設定
    
    message.temperature = 23.5f;
    message.has_temperature = true;  // 重要: has_* フラグを設定
    
    // 通常フィールド(has_* フラグは不要)
    message.active = true;
    
    // エンコード用ストリームを作成
    pb_ostream_t ostream = pb_ostream_from_buffer(buffer, sizeof(buffer));
    
    // メッセージをエンコード
    if (!pb_encode(&ostream, example_OptionalMessage_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);
    
    // エンコードデータの16進ダンプを出力
    printf("Encoded data: ");
    for (size_t i = 0; i < message_length; i++) {
        printf("%02x ", buffer[i]);
    }
    printf("\n");
    
    // --- デコード ---
    example_OptionalMessage decoded = example_OptionalMessage_init_zero;
    
    // デコード用ストリームを作成
    pb_istream_t istream = pb_istream_from_buffer(buffer, message_length);
    
    // メッセージをデコード
    if (!pb_decode(&istream, example_OptionalMessage_fields, &decoded)) {
        printf("Decoding failed: %s\n", PB_GET_ERROR(&istream));
        return 1;
    }
    
    // デコードされた値を出力
    printf("Decoded values:\n");
    if (decoded.has_id) {
        printf("  id: %u\n", decoded.id);
    } else {
        printf("  id: (not set)\n");
    }
    
    if (decoded.has_name) {
        printf("  name: %s\n", decoded.name);
    } else {
        printf("  name: (not set)\n");
    }
    
    if (decoded.has_temperature) {
        printf("  temperature: %f\n", decoded.temperature);
    } else {
        printf("  temperature: (not set)\n");
    }
    
    printf("  active: %s\n", decoded.active ? "true" : "false");
    
    return 0;
}

コンパイルコマンド

nanopb を使って例をコンパイルします。NanoPB は通常、ソースファイルをプロジェクトに直接含めて使用します。

compile_optional_example.sh
g++ -o optional_example optional_example.cpp optional.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_optional.py
import optional_pb2

# バイナリデータを読み込む
with open('encoded.bin', 'rb') as f:
    data = f.read()

# デコード
msg = optional_pb2.OptionalMessage()
msg.ParseFromString(data)

print("Python decoded values:")
print(f"  id: {msg.id if msg.HasField('id') else '(not set)'}")
print(f"  name: {msg.name if msg.HasField('name') else '(not set)'}")
print(f"  temperature: {msg.temperature if msg.HasField('temperature') else '(not set)'}")
print(f"  active: {msg.active}")

まず、Python の protobuf 定義をコンパイルします。

compile_python_optional.sh
protoc --python_out=. optional.proto

次に、エンコードされたデータをファイルに保存するように C++ の例を変更します。

save_encoded_optional.cpp
// エンコード後にこれを追加:
FILE *f = fopen("encoded.bin", "wb");
fwrite(buffer, 1, message_length, f);
fclose(f);

オプショナルフィールドが未設定の例

一部のオプショナルフィールドが設定されていない例を示します。

optional_partial_example.cpp
#include <stdio.h>
#include <string.h>
#include "optional.pb.h"
#include "pb_encode.h"
#include "pb_decode.h"

int main() {
    uint8_t buffer[256];
    size_t message_length;
    
    // --- エンコード ---
    example_OptionalMessage message = example_OptionalMessage_init_zero;
    
    // 一部のオプショナルフィールドのみ設定
    message.id = 42;
    message.has_id = true;
    
    // name と temperature は未設定(has_* フラグは false のまま)
    
    // 通常フィールドは常に設定
    message.active = true;
    
    pb_ostream_t ostream = pb_ostream_from_buffer(buffer, sizeof(buffer));
    
    if (!pb_encode(&ostream, example_OptionalMessage_fields, &message)) {
        printf("Encoding failed: %s\n", PB_GET_ERROR(&ostream));
        return 1;
    }
    
    message_length = ostream.bytes_written;
    printf("Encoded %zu bytes (partial)\n", message_length);
    
    // --- デコード ---
    example_OptionalMessage decoded = example_OptionalMessage_init_zero;
    
    pb_istream_t istream = pb_istream_from_buffer(buffer, message_length);
    
    if (!pb_decode(&istream, example_OptionalMessage_fields, &decoded)) {
        printf("Decoding failed: %s\n", PB_GET_ERROR(&istream));
        return 1;
    }
    
    printf("Decoded values:\n");
    printf("  id: %s\n", decoded.has_id ? "set" : "not set");
    printf("  name: %s\n", decoded.has_name ? "set" : "not set");
    printf("  temperature: %s\n", decoded.has_temperature ? "set" : "not set");
    printf("  active: %s\n", decoded.active ? "true" : "false");
    
    return 0;
}

ポイント

  • オプショナルフィールド: proto3 で optional キーワードを使用します
  • has_ フラグ*: NanoPB は各オプショナルフィールドに対して has_fieldname ブールフラグを生成します
  • エンコード: フィールドの値と has_* フラグの両方を true に設定します
  • デコード: オプショナルフィールドの値を使用する前に has_* フラグを確認します
  • 通常フィールド: 非オプショナルフィールドには has_* フラグがありません
  • デフォルト値: 設定されていないオプショナルフィールドはデフォルト値(0、空文字列など)を持ちます
  • 容量削減: 未設定のオプショナルフィールドはエンコードされたメッセージに含まれません

オプショナルフィールドを使う場面

  • フィールドがメッセージインスタンスによって存在したりしなかったりする場合
  • 「未設定」と「デフォルト値に設定」を区別したい場合
  • 未使用フィールドを省略して帯域を節約したい場合
  • フィールドが特定のコンテキストでのみ関連する場合

期待される出力(完全な例)

optional_full_expected_output.txt
Encoded 19 bytes
Encoded data: 08 2a 12 07 53 65 6e 73 6f 72 31 1d 00 00 bc 41 30 01 
Decoded values:
  id: 42
  name: Sensor1
  temperature: 23.500000
  active: true

期待される出力(部分的な例)

optional_partial_expected_output.txt
Encoded 4 bytes (partial)
Encoded data: 08 2a 30 01 
Decoded values:
  id: set
  name: not set
  temperature: not set
  active: true

オプショナルフィールドが省略されるため、部分的なエンコードがはるかに小さい(4 バイト対 19 バイト)ことに注目してください。

その他の NanoPB 記事


同じカテゴリの類似記事をチェック: 組み込み C/C++ Protocol Buffers