[英]Google protobuf repeated fields with C++
我需要使用 C++ 中的序列化鍵值對構建以下Metadata
消息。
message MetadataValue {
string key = 1;
google.protobuf.Value value = 2;
}
message Metadata {
repeated MetadataValue metadata = 1;
}
因此,我可以從 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
}
}
我的問題是我的方法是否正確? 在上述情況下是否有更好的選擇以及如何設置 google.protobuf.Value ? 非常感謝帶有答案的簡單代碼片段。
我認為這段代碼有效,我只是檢查了 protoc 生成的 API。
如果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
}
}
我正在使用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.