ProtoBuf如何在c++中使用

18 篇文章 0 订阅

我使用protobuf版本号:protobuf-2.5.0


vs版本:vs2010


解压protobuf-2.5.0,解压后内容如下:



这里写图片描述



进入上面画线的vsprojects文件夹


这里写图片描述


这里写图片描述



这里写图片描述


这里写图片描述


接着打开记事本,注意我的用词是记事本,而非文本文档

建两个文件:


这里写图片描述



guozhu.proto :

这里写图片描述


上面文件写好后,保存时,注意如下:
这里写图片描述



test.bat :


这里写图片描述




这里写图片描述


此时双击test.bat文件


这里写图片描述


这里写图片描述


这里写图片描述


这里写图片描述


这里写图片描述



这里写图片描述


这里写图片描述



这里写图片描述


这里写图片描述


这里写图片描述


这里写图片描述


这里写图片描述


这里写图片描述



这里写图片描述


到此为止,protobuf在C++的环境搭建和准备工作已经做完,测试一下吧:


这里写图片描述


运行如下:
这里写图片描述


注意如下:
protobuf下载包的大小是:1.78M,其它的我试验过,编译会失败


这里写图片描述


这里写图片描述


FR:海涛高软(hunk Xu) QQ技术交流群:386476712

  • 3
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的使用 Google ProtobufC++ 示例: 假设我们已经定义了一个 `person.proto` 文件,其包含了一个 `Person` 消息类型: ```protobuf syntax = "proto3"; message Person { string name = 1; int32 age = 2; string email = 3; } ``` 接下来,我们需要使用 `protoc` 工具将 `.proto` 文件编译成 C++ 代码。在命令行输入以下命令: ``` $ protoc --cpp_out=. person.proto ``` 这将在当前目录下生成 `person.pb.h` 和 `person.pb.cc` 两个文件,其包含了 `Person` 消息类型的 C++ 代码。 接下来,我们可以在我们的 C++ 代码使用 `Person` 类型。以下是一个简单的示例: ```c++ #include <iostream> #include <fstream> #include "person.pb.h" using namespace std; void write_to_file(const string& filename, const Person& person) { // 将 Person 对象写入文件 fstream output(filename, ios::out | ios::trunc | ios::binary); if (!person.SerializeToOstream(&output)) { cerr << "Failed to write person to file." << endl; } } bool read_from_file(const string& filename, Person& person) { // 从文件读取 Person 对象 fstream input(filename, ios::in | ios::binary); if (!person.ParseFromIstream(&input)) { cerr << "Failed to read person from file." << endl; return false; } return true; } int main() { // 创建一个 Person 对象 Person person; person.set_name("John"); person.set_age(30); person.set_email("john@example.com"); // 将 Person 对象写入文件 write_to_file("person.txt", person); // 从文件读取 Person 对象 Person new_person; if (read_from_file("person.txt", new_person)) { cout << "Name: " << new_person.name() << endl; cout << "Age: " << new_person.age() << endl; cout << "Email: " << new_person.email() << endl; } return 0; } ``` 以上代码演示了如何创建一个 `Person` 对象,并将其写入文件。然后从文件读取 `Person` 对象,并打印出其属性。注意,我们使用 `SerializeToOstream` 和 `ParseFromIstream` 方法来序列化和反序列化 `Person` 对象。 当然,这只是一个简单的示例。Google Protobuf 还有很多其他的用法和功能,可以根据实际需要进行学习和使用
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值