基于原型文件调用setter和getter方法

问题描述 投票:0回答:1

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

这是我声明原始文件的方式:

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个回答
0
投票

这里是根据您的格式(序列化和反序列化)的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
© www.soinside.com 2019 - 2024. All rights reserved.