pepe1
pepe1

Reputation: 235

How to create object from repeated type protobuf

What I am looking for is a function that returns the message of a repeated field

I know there is Reflection::AddMessage which has the return type that I want but I do not want to add a message, just return an object of that message.

Here is an example of what I am trying to do let's say I have in the .proto file a message:

message Bar{
    uint32 t x = 1;
    uint64 t y = 2;
}

message Foo{
    repeated Bar myMessage = 1;
}

I am using reflection to iterate through the Foo message and I want to be able to do something like this:

Message* Msg = createMessage(refl->FooMsg, FieldDesc) 

I know there is also GetRepeatedMessage but that requires index.

Upvotes: 0

Views: 1729

Answers (1)

Marko Bencik
Marko Bencik

Reputation: 396

First of all when the protobuf compiler generates the code for compiling you get an accessor function in the interface. The are functions mutable_nameOf_message() which returns the entire repeated field which is a std::vector in c++, or mutable_nameOf_message( index ) which gives you the specified element.

Now if you do not want to use Bar then you d'not need too.

message ArrayOfBar 
{
    repeated Bar arrayOfBar = 0;

    message Bar{
        uint32 t x = 1;
        uint64 t y = 2;
    }
}

If thats what you have hade in mind you could also be do something like this.

std::vector<Bar> arrayOfBars;

But that idea needs refinement because of the internal specifics of the Protobuf. Some unwanted behavior might occur with something like that.

Upvotes: 1

Related Questions