程式語言 - GNU - C/C++ - NanoPB Proto2(Options)



參考資訊:
https://www.jianshu.com/p/cad578f48e0a
https://github.com/nanopb/nanopb/tree/master
https://github.com/afiskon/cpp-protobuf-example/tree/master
https://stackoverflow.com/questions/47704968/protoc-command-not-found-linux
https://stackoverflow.com/questions/62707863/how-to-encode-messages-with-map-using-google-protobuf-in-javascript-protocol

main.proto

syntax = "proto2";

message test {
    required string v1 = 1;
    required int32  v2 = 2;

    required _opt opt  = 3;
    message _opt {
        required string v1 = 1;
        required int32  v2 = 2;
    }
}

main.options

test.v1      max_size:255
test._opt.v1 max_size:255

main.c

#include <stdio.h>
#include <pb_encode.h>
#include <pb_decode.h>
 
#include "main.pb.h"
 
int main(int argc, char **argv)
{
    char buf[255] = {0};
     
    test org = test_init_zero;
    strcpy(org.v1, "t1");
    org.v2 = 100;
    strcpy(org.opt.v1, "t2");
    org.opt.v2 = 200;
    pb_ostream_t os1 = pb_ostream_from_buffer(buf, sizeof(buf));
    pb_encode(&os1, test_fields, &org);
 
    test out = test_init_zero;
    pb_istream_t is2 = pb_istream_from_buffer(buf, os1.bytes_written);
    pb_decode(&is2, test_fields, &out);
 
    printf("v1: %s\n", out.v1);
    printf("v2: %d\n", out.v2);
    printf("opt.v1: %s\n", out.opt.v1);
    printf("opt.v2: %d\n", out.opt.v2);
    return 0;
}

編譯、執行

$ protoc --nanopb_out=-v:. main.proto
    Reading options from ./main.options
    Options for main.proto:
    Options for test:
    Options for test.v1: max_size: 255

    Options for test.v2:
    Options for test.opt:
    Options for test._opt:
    Options for test._opt.v1: max_size: 255

    Options for test._opt.v2:
    Reading options from ./main.options
    Options for main.proto:
    Options for test:
    Options for test.v1: max_size: 255

    Options for test.v2:
    Options for test.opt:
    Options for test._opt:
    Options for test._opt.v1: max_size: 255

    Options for test._opt.v2:

$ gcc main.c -o test main.pb.c -I. -lprotobuf-nanopb
$ ./test
    v1: t1
    v2: 100
    opt.v1: t2
    opt.v2: 200