简体   繁体   中英

protobuf, How to travel all set fields in a protobuf message which I dont know in detail?(C++)

I want to travel the field has been set in a unknown protobuf message. I tried

for (int i = 0; i < chk_des->field_count(); ++i) {
    const ::google::protobuf::FieldDescriptor* chk_field = chk_des->field(i);
    (do somethin...)
}

It just travel all field. I want to travel setted field.

You retrieve a reflection object:

virtual const Reflection * 
    Message::GetReflection() const

Get the Reflection interface for this Message, which can be used to read and modify the fields of the Message dynamically (in other words, without knowing the message type at compile time).

After that you can use for example:

virtual bool Reflection::HasField(const Message & message, const FieldDescriptor * field) const = 0

Check if the given non-repeated field is set.

So notice that you also need to pass the field descriptor from your code snippet.

const FieldDescriptor * 
    Descriptor::field(
        int index) const

Gets a field by index, where 0 <= index < field_count().

These are returned in the order they were defined in the .proto file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM