Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setting repeated field in protobuf using reflection

I have a protobuf message similar to this:

message foo {
   repeated double values = 1;
}

I am using reflection (as explained here) to set the values like this in my C++ code

auto desc = protoMsg.GetDescription();
auto refl = protoMsg.GetReflection();
auto fd = desc->FindFieldByNumber(1); // run time value

assert(fd->is_repeated());
for (int i = 0; i < vect.size(); ++i)
   refl->SetRepeatedDouble(&protoMsg, fd, i, vect[i]);

My application is crashing inside SetRepeatedDouble function. Has anyone tried to do something like this before? (set values using reflection? Note that I have to use reflection due to dynamic nature of my application. I have simplified above code slightly not to do that for now)

Also any tips on how to possible debug this are appreciated.

like image 635
skgbanga Avatar asked Sep 21 '25 13:09

skgbanga


1 Answers

SetRepeatedDouble() overwrites an already-present element of the array. For your code to work, the repeated field must already have a size at least equal to vect.size(), otherwise you are overrunning the array, which would indeed cause a crash (or worse). If you started with an empty message instance, then you need to add the values instead of setting them, like so:

for (int i = 0; i < vect.size(); ++i)
    refl->AddDouble(&protoMsg, fd, vect[i]);
like image 97
Kenton Varda Avatar answered Sep 23 '25 02:09

Kenton Varda