// proto_example.proto
syntax = "proto3";
message Person {
string name = 1;
int32 id = 2;
string email = 3;
}
// 编译命令: protoc --cpp_out=. proto_example.proto
// main.cpp
#include <iostream>
#include <fstream>
#include "proto_example.pb.h"
int main() {
// 创建一个Person对象并设置字段值
tutorial::Person person;
person.set_name("John Doe");
person.set_id(1234);
person.set_email("johndoe@example.com");
// 序列化到字符串
std::string output;
if (!person.SerializeToString(&output)) {
std::cerr << "Failed to serialize." << std::endl;
return -1;
}
// 反序列化从字符串
tutorial::Person new_person;
if (!new_person.ParseFromString(output)) {
std::cerr << "Failed to parse." << std::endl;
return -1;
}
// 打印反序列化后的信息
std::cout << "Name: " << new_person.name() << std::endl;
std::cout << "ID: " << new_person.id() << std::endl;
std::cout << "Email: " << new_person.email() << std::endl;
return 0;
}
proto_example.proto 文件中定义了一个简单的 Person 消息,包含三个字段:name、id 和 email。protoc 命令将 .proto 文件编译为 C++ 代码。这会生成对应的 .pb.h 和 .pb.cc 文件。main.cpp 中,创建一个 Person 对象并设置其字段值,然后将其序列化为字符串。Person 对象,并打印出反序列化后的信息。如果你需要进一步的帮助或有其他问题,请告诉我!
上一篇:c++ orm
下一篇:c++ vector 遍历
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站