如何使用Protobuf的反射修改地图
我正在使用C ++ 14项目中的ProtoBuf3。有一些功能,可以返回google :: ProtoBuf :: Message*
作为RPC请求,我需要做的是设置其字段。因此,我需要使用ProtoBuf3的反射。
这是一个原始文件:
syntax="proto3";
package srv.user;
option cc_generic_services = true;
message BatchGetUserInfosRequest {
uint64 my_uid = 1;
repeated uint64 peer_uids = 2;
map<string, string> infos = 3;
}
message BatchGetUserInfosResponse {
uint64 my_uid = 1;
string info = 2;
}
Service UserSrv {
rpc BatchGetUserInfos(BatchGetUserInfosRequest) returns (BatchGetUserInfosResponse);
};
现在我打了一个函数,它返回google :: protobuf :: message*
,指向对象batchgetuserinfosrequest
,然后尝试设置其字段。
// msg is a Message*, pointing to an object of BatchGetUserInfosRequest
auto descriptor = msg->GetDescriptor();
auto reflection = msg->GetReflection();
auto field = descriptor->FindFieldByName("my_uid");
reflection->SetUInt64(msg, field, 1234);
auto field2 = descriptor->FindFieldByName("peer_uids");
reflection->GetMutableRepeatedFieldRef<uint64_t>(msg, field2).CopyFrom(peerUids); // peerUids is a std::vector<uint64_t>
如您所见,我可以设置my_uid
和peer_uids
如上所述,但是对于字段infos
,它是google :: ProtoBuf :: MAP
,我不知道如何使用反射机制设置它。
I'm working with Protobuf3 in my C++14 project. There have been some functions, which returns the google::protobuf::Message*
s as a rpc request, what I need to do is to set their fields. So I need to use the reflection of Protobuf3.
Here is a proto file:
syntax="proto3";
package srv.user;
option cc_generic_services = true;
message BatchGetUserInfosRequest {
uint64 my_uid = 1;
repeated uint64 peer_uids = 2;
map<string, string> infos = 3;
}
message BatchGetUserInfosResponse {
uint64 my_uid = 1;
string info = 2;
}
Service UserSrv {
rpc BatchGetUserInfos(BatchGetUserInfosRequest) returns (BatchGetUserInfosResponse);
};
Now I called a function, which returns a google::protobuf::Message*
, pointing an object BatchGetUserInfosRequest
and I try to set its fields.
// msg is a Message*, pointing to an object of BatchGetUserInfosRequest
auto descriptor = msg->GetDescriptor();
auto reflection = msg->GetReflection();
auto field = descriptor->FindFieldByName("my_uid");
reflection->SetUInt64(msg, field, 1234);
auto field2 = descriptor->FindFieldByName("peer_uids");
reflection->GetMutableRepeatedFieldRef<uint64_t>(msg, field2).CopyFrom(peerUids); // peerUids is a std::vector<uint64_t>
As you see, I can set my_uid
and peer_uids
as above, but for the field infos
, which is a google::protobuf::Map
, I don't know how to set it with the reflection mechanism.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您深入研究,您会在
proto3
中找到map
在repotedfield
上实现:从
:
If you dig deep into the source code, you would find out the
map
inproto3
is implemented on theRepeatedField
:Inspired by the test code from protobuf, this works for me:
The output: