如何在C++ protobuf中反序列化一个消息中的重复消息

huangapple go评论59阅读模式
英文:

How to deserialize repeated message of one of message in C++ protobuf

问题

我有一个protobuf消息定义如下:

message TestWordOne {
uint32 word = 1;
}

message TestWordTwo {
repeated TestWordOne words = 1;
}

message TestMessage {
oneof payload {
TestWordTwo test_data = 1;
<some more stuff here>
}
}


现在,我可以按以下方式进行序列化:

TestMessage sentMessage;
TestMessage recvMessage;

TestWordTwo* data_test(new TestWordTwo);
for (int i=0; i<5; i++)
{
TestWordOne* oneWord = data_test->add_words();
oneWord->set_word(i);
}


然后使用outputstream进行序列化:

sentMessage.SerializeToOstream(&outputStream)


然而,当我执行以下操作:

recvMessage.ParseFromIstream(&outputStream)


我不知道如何逐个获取recVMessage中的单词。有什么建议吗?

我尝试使用Descriptor和Reflection,但所有可用的示例都没有说明如何在我的情况下继续。
英文:

I have a protobuf such as:

message TestWordOne {
    uint32 word = 1;
}

message TestWordTwo {
    repeated TestWordOne words = 1;
}

message TestMessage {
    oneof payload {
        TestWordTwo test_data = 1;
        &lt;some more stuff here&gt;
    }
}

Now, I can serialize in such a way:

TestMessage sentMessage;
TestMessage recvMessage;

    TestWordTwo* data_test(new TestWordTwo);
    for (int i=0; i&lt;5; i++)
    {
         TestWordOne* oneWord = data_test-&gt;add_words();
         oneWord-&gt;set_word(i);
    }

Then serialize it with outputstream

sentMessage.SerializeToOstream(&amp;outputStream)

However, I when I

recvMessage.ParseFromIstream(&amp;outputStream)

I have no idea on how to get words from recVMessage, one by one. Any tips?

I tried using Descriptor and Reflection, but all available examples do not specify on how to proceed in my case.

答案1

得分: 1

在*.pb.h文件中很容易找到:

for (int i = 0; i < 5; i++) {
    const TestWordOne& oneWord = data_test->words(i);
    TestWordOne* oneWordMutable = data_test->mutable_words(i);
}
英文:

It's easy to find in *.pb.h:

for (int i=0; i&lt;5; i++) {
     const TestWordOne&amp; oneWord = data_test-&gt;words(i);
     TestWordOne* oneWordMutable = data_test-&gt;mutable_words(i);
}

huangapple
  • 本文由 发表于 2023年2月8日 08:44:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/75380391.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定