简体   繁体   中英

Google protobuf repeated fields with C++

I have a requirement to build the following Metadata message using serialized key value pairs in C++.

message MetadataValue {
  string key = 1;
  google.protobuf.Value value = 2;
}

message Metadata {
  repeated MetadataValue metadata = 1;
}

So I can have the values for MetadataValue from the following for statement in C++.

Metadata metadata; 
  if (buffer.has_value()) {
    auto pairs = buffer.value()->pairs();
    for (auto &p : pairs) {
      MetadataValue* metadataValue = metadata.add_metadata();
      metadataValue->set_key(std::string(p.first));
      // I don't know how to set the value for google.protobuf.Value 
    }
  }

My question is whether my approach is correct? Are there better alternatives and how to set the google.protobuf.Value in that above scenario? A simple code snippet with the answer is much appreciated.

I think this code works, I just checked the generated APIs by protoc.

If the typeof(p.second) is not a google::protobuf::Value , you need to add conversion like

auto v = google::protobuf::Value();
v.set_number_value(p.second);
// or p.second is string
// v.set_string_value(p.second);
Metadata metadata; 
  if (buffer.has_value()) {
    auto pairs = buffer.value()->pairs();
    for (auto &p : pairs) {
      MetadataValue* metadataValue = metadata.add_metadata();
      metadataValue->set_key(std::string(p.first));
      *metadataValue->mutable_value() = p.second;
      // I don't know how to set the value for google.protobuf.Value 
    }
  }

And I am using protoc version 3

syntax = "proto3";
import "google/protobuf/struct.proto";
message MetadataValue {
  string key = 1;
  google.protobuf.Value value = 2;
}

message Metadata {
  repeated MetadataValue metadata = 1;
}

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