简体   繁体   English

Google protobuf 重复字段与 C++

[英]Google protobuf repeated fields with C++

I have a requirement to build the following Metadata message using serialized key value pairs in C++.我需要使用 C++ 中的序列化键值对构建以下Metadata消息。

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++.因此,我可以从 C++ 中的以下 for 语句中获取MetadataValue的值。

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?在上述情况下是否有更好的选择以及如何设置 google.protobuf.Value ? A simple code snippet with the answer is much appreciated.非常感谢带有答案的简单代码片段。

I think this code works, I just checked the generated APIs by protoc.我认为这段代码有效,我只是检查了 protoc 生成的 API。

If the typeof(p.second) is not a google::protobuf::Value , you need to add conversion like如果typeof(p.second)不是google::protobuf::Value ,则需要添加转换,例如

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我正在使用protoc版本 3

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

message Metadata {
  repeated MetadataValue metadata = 1;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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