【问题标题】:Calling the setter and getter method based on the proto file基于proto文件调用setter和getter方法
【发布时间】:2020-04-08 03:16:19
【问题描述】:

我刚开始使用 GRPC,但在设置和获取参数时遇到了麻烦。

这是我声明我的 proto 文件的方式:

syntax="proto3";

package student;

message Student {
  string name = 1;
   int32 age = 2;
}

然后我使用命令编译生成头文件和cpp文件:

protoc -I=./ --cpp_out=./ ./student.proto

现在我如何设置和获取学生的年龄:

#include <stdio.h>
#include "student.pb.h"

int main() {
      puts("Hello");
      // Now set and get the age
      return 0;
}

【问题讨论】:

    标签: c++ c protocol-buffers grpc


    【解决方案1】:

    根据您的格式(序列化和反序列化),这是一个 C++ 示例:

    int main()
    {
        // Serailization
    
        student::Student s1;
        s1.set_name("XYZ");
        s1.set_age(20);
    
        const auto serializedData = s1.SerializeAsString();
    
        // Send/Store Serialized Data
    
        // Deserialization
    
        student::Student s2;
        if ( !s2.ParseFromString( serializedData ) )
        {
            std::cerr << "Deserialzation failed!\n";
            return -1;
        }
    
        std::cout << "Name: " << s2.name() << '\n';
        std::cout << "Age : " << s2.age() << '\n';
    
        return 0;
    }
    

    输出:

    Name: XYZ
    Age : 20
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-14
      • 2017-09-09
      • 1970-01-01
      • 2017-08-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多