Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

protobuf c++

作者:淡漠伤悲   发布日期:2025-10-07   浏览:15

// 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;
}

解释说明:

  1. 定义 Protocol Buffer 消息:在 proto_example.proto 文件中定义了一个简单的 Person 消息,包含三个字段:nameidemail
  2. 编译 Protocol Buffer 文件:使用 protoc 命令将 .proto 文件编译为 C++ 代码。这会生成对应的 .pb.h.pb.cc 文件。
  3. 创建和序列化消息:在 main.cpp 中,创建一个 Person 对象并设置其字段值,然后将其序列化为字符串。
  4. 反序列化和打印消息:将序列化的字符串反序列化回 Person 对象,并打印出反序列化后的信息。

如果你需要进一步的帮助或有其他问题,请告诉我!

上一篇:c++ orm

下一篇:c++ vector 遍历

大家都在看

c++闭包

c++单引号和双引号的区别

c++ 注释

c++如何判断素数

c++格式化字符串

c++ orm框架

队列c++

c++freopen怎么用

进制转换c++代码

c++ 获取系统时间

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站