c++的PB的Message根据filed获取值
时间: 2024-02-24 18:54:30 浏览: 94
在C++中,可以使用`google::protobuf::Message`类的`GetReflection()`方法来获取`google::protobuf::MessageReflection`对象,然后使用该对象的`GetField()`方法获取指定字段的值。以下是一个例子:
假设我们有一个Person.proto文件,其中定义了一个Person消息类型:
```
syntax = "proto3";
message Person {
string name = 1;
int32 age = 2;
repeated string hobbies = 3;
}
```
在C++中,我们可以通过以下方式获取Person消息中的name字段的值:
```
#include <iostream>
#include "person.pb.h"
int main() {
Person person;
person.set_name("John");
person.set_age(30);
person.add_hobbies("Reading");
person.add_hobbies("Traveling");
const auto& reflection = person.GetReflection();
const auto* descriptor = person.GetDescriptor();
const auto* field_descriptor = descriptor->FindFieldByName("name");
std::string name = reflection.GetString(person, field_descriptor);
std::cout << name << std::endl; // 输出 "John"
return 0;
}
```
这里我们先创建了一个Person对象,并设置了name、age和hobbies字段的值。然后使用`GetReflection()`方法获取`google::protobuf::MessageReflection`对象,使用`GetDescriptor()`方法获取`google::protobuf::Descriptor`对象,使用该对象的`FindFieldByName()`方法获取name字段的`google::protobuf::FieldDescriptor`对象。最后,我们使用`GetString()`方法获取name字段的值。同样的方式可以用来获取age和hobbies字段的值。
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)