C++中proto的field與序號index的對應關係查找

假設有一個proto message定義如下:

message Example {
  optional bool a = 1;
  optional bool b = 2;
};

如果想在代碼裏知道a這個field定義時的給的序號是多少(這裏是1):

Example obj;
std::cout << obj.GetDescriptor()->FindFieldByName("a")->number() << std::endl;
// output: 1

如果沒有名字爲a的字段,obj.GetDescriptor()->FindFieldByName("a")的結果是一個空指針。

 

如果想知道序號1對應的field的name:

Example obj;
std::cout << obj.GetDescriptor()->FindFieldByNumber(1)->name() << std::endl;
// output: a

如果沒有序號爲1的字段,obj.GetDescriptor()->FindFieldByNumber(1)的結果是一個空指針。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章