Proto:
环境配置(以c++为例):
1. 安装 protobuf 编译器 (protoc)
Ubuntu/Debian:
sudo apt install protobuf-compiler libprotobuf-dev
macOS (Homebrew):
brew install protobuf
Windows:
从 GitHub Releases 下载 protoc-<version>-win64.zip,解压后将 bin 目录添加到系统 PATH。
验证安装:
protoc --version
2. 编写 .proto 文件(以person.proto为例)
- 创建一个
person.proto文件:
syntax = "proto3";
package tutorial;
message Person {
string name = 1;
int32 id = 2;
string email = 3;
}
3. 生成 C++ 代码
protoc --cpp_out=. person.proto
- 会在.proto同级目录下生成
person.pb.h和person.pb.cc两个文件。
4. 在 C++ 项目中使用
CMakeLists.txt 示例:
cmake_minimum_required(VERSION 3.10)
project(ProtoExample)
find_package(Protobuf REQUIRED)
add_executable(main main.cpp person.pb.cc)
target_include_directories(main PRIVATE ${Protobuf_INCLUDE_DIRS})
target_link_libraries(main PRIVATE ${Protobuf_LIBRARIES})
main.cpp 示例:
#include <iostream>
#include <fstream>
#include "person.pb.h"
int main() {
// 初始化
GOOGLE_PROTOBUF_VERIFY_VERSION;
// 创建对象并赋值
tutorial::Person person;
person.set_name("张三");
person.set_id(123);
person.set_email("zhangsan@example.com");
// 序列化到文件
std::ofstream ofs("person.bin", std::ios::binary);
person.SerializeToOstream(&ofs);
ofs.close();
// 反序列化
tutorial::Person person2;
std::ifstream ifs("person.bin", std::ios::binary);
person2.ParseFromIstream(&ifs);
std::cout << "Name: " << person2.name() << std::endl;
std::cout << "ID: " << person2.id() << std::endl;
std::cout << "Email: " << person2.email() << std::endl;
// 清理
google::protobuf::ShutdownProtobufLibrary();
return 0;
}
5. 编译运行
mkdir build && cd build
cmake ..
make
./main
碎碎念
- 可算期末考完了,打算自己手写个RPC框架
