我刚开始使用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 ++示例:
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