簡體   English   中英

如何對重復的 google.protobuf.any 進行編碼?

[英]How to encode a repeated google.protobuf.any?

我有一條消息,我想將它打包成任何重復的 google 原型類型:: 有沒有辦法對重復的任何消息類型進行編碼?

我什至可以在 google.protobuf.any 中使用重復標簽嗎?

message Onesensor{
    string name=1
    string type=2
    int32_t reading=3
}


/** Any Message **/
message RepeatedAny{
repeated google.protobuf.any sensors = 1;
}

我正在尋找一個示例,目前使用 nanopb 進行編碼。

當然,這只是一條常規消息。

https://github.com/nanopb/nanopb/tree/master/tests/any_type展示了如何對單個 Any 消息進行編碼,對許多消息進行編碼就像對任何數組進行編碼。 您可以在靜態分配、動態分配或使用回調之間進行選擇。 或者您可以一次只將單個子字段編碼到輸出流中,因為連接編碼后的數組以 protobuf 格式連接。

我想我發現了我的問題,我不能使用(google.protobuf.any 上的重復標簽,因為我想在最終二進制文件中附加RepeatedAny消息):

message Onesensor{
    string name=1
    string type=2
    int32_t reading=3
}

message RepeatedAny{
repeated google.protobuf.any sensors = 1;
}

相反,我應該使用這樣的東西:

message Onesensor{
    string name=1
    string type=2
    int32_t reading=3
}

message SensorAny{
google.protobuf.any sensor = 1;
}

message RepeatedAny{
repeated SensorAny sensors = 1;
}

我不應該在 google.protobuf.any 上使用重復的標簽,我應該在包含 google.protobuf.any 的消息上使用它,以便 protobinary 可以包含格式 (sensors1), (sensors2).. ...(sensorsN),一條或多條SensorAny消息。

下面是示例代碼,如果將來有人發現nanopb的這個問題:

    /* First encode the SensorAny message by setting the value of the first field,
       The first field of this message is of type google.protobuf.any, so it should have
       1. sensor.type_url
       2. sensor.value
    */

    void* pBufAny = calloc(1, sBufSize);
    pb_ostream_t ostream_any = pb_ostream_from_buffer(pBufAny, sBufSize);
    SensorAny SensorAnyProto = SensorAny_init_default;
    SensorAnyProto.has_message = true;
    SensorAnyProto.sensor.type_url.arg = "type.googleapis.com/SensorAny.proto";
    SensorAnyProto.sensor.type_url.funcs.encode = Proto_encode_string;
    ProtoEncodeBufferInfo_t BufInfo = {
            .Buffer = pBuf, /* I have already filled and encoded Onesensor message previously as pBuf */
            .BufferSize = ostream.bytes_written,
    };
    SensorAnyProto.sensor.value.funcs.encode = Proto_encode_buffer;
    SensorAnyProto.sensor.value.arg = &BufInfo;
    pb_encode(&ostream_any, SensorAny_fields, &SensorAnyProto);
    free(pBuf);


    // Now Use the above encoded Any message buffer pBufAny to set the first repeated field in RepeatedAny

    RepeatedAny SensorAnyRepeated = RepeatedAny_init_default;
    ProtoEncodeBufferInfo_t AnyBufInfo = {
            .Buffer = pBufAny,
            .BufferSize = ostream_any.bytes_written,
    };

    AnyRepeated.sensors.arg=&AnyBufInfo;
    AnyRepeated.sensors.funcs.encode = Proto_encode_buffer;

    void* pBufAnyRepeated = calloc(1, sBufSize);
    pb_ostream_t ostream_repeated = pb_ostream_from_buffer(pBufAnyRepeated, sBufSize);
    !pb_encode(&ostream_repeated, RepeatedAny_fields, &AnyRepeated);
    free(pBufAny);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM