user2896235
user2896235

Reputation: 359

Issue in reading repeated fields from protocol buffers in C++

org.proto

message Optimize {
    required int element_size = 1;
    required string element_name = 2;
}

message nodes {
    repeated Optimize = 1;
}

Have this decoding function:

DecodeNodeMsg(char *msg, int size)
{

    Org::nodes node;
    int element_size;
    string element_name;
    int NumofElem = 0;

    node.ParseFromArray((void *)msg, size);

    for (int i = 0; i < nodes.Optimize().size(); i++)
    {
        element_size = nodes.Optimize(i).element_size();
        element_name = nodes.Optimize(i).element_name();
        cout << "size" << element_size << endl;
        cout << "name" << element_name << endl;
        NumofElem++;
    }
    cout << "number of" << NumofElem << endl;
}

I am encoding a nodes message with three Optimize messages in it. and calling this decode function. Encoding part is an old code which is working fine from long time. So i dont suspect the encoding function.

In the decode function, I see that the NumofElem is correctly printed as three. However, i see that both element_size & element_name are just garbage. Integer has some junk value and string has a binary data.

I am having this issue only if this repeated fields. If fields are required/optional fields, then i dont have this issue.

Could some one has similar issue... ? if so any clues on how to fix this ?

Thanks, Kiran

Upvotes: 1

Views: 11459

Answers (2)

jhoffmann
jhoffmann

Reputation: 31

The function deserializes the buffer into the local variable node, but the loop references nodes. I'd also validate the return value from ParseFromArray.

Upvotes: 1

HughB
HughB

Reputation: 373

I don't see where you are actually decoding a message. I see you creating a new node object, but then calling Org::nodes() which looks wrong. I think you need to access the Optimize elements like this:

for (int i = 0; i < node->optimize_size(); i++)
{
    element_size = node->optimize(i).element_size();
    element_name = node->optimize(i).element_name();
    cout << "size" << element_size << endl;
    cout << "name" << element_name << endl;
    NumofElem++;
}

But again I think your nodes object needs to be decoded from something. The mutable methods allow you to set data. There's also the ParseFrom methods. Also in my proto files I number the elements in a message. See https://developers.google.com/protocol-buffers/docs/overview

 message nodes {
   repeated Optimize = 1;
 }

Upvotes: 1

Related Questions