Protobuf 了解

本文详细介绍了如何在Visual Studio环境下搭建Protocol Buffers (Protobuf) C++工程,包括从获取protobuf库到配置工程,编写.proto文件,生成及应用编译后的文件。通过实例展示了如何序列化和反序列化数据,以及解决编译问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Protocol Buffers 是一种结构数据序列化方法,可以将C++中定义的存储类的内容与二进制序列串相互转换,主要用于数据传输或数据存储,可类比XML、JSON,而XML、JSON基于文本格式,protobuf是二进制格式,所以比XML、JSON更小(3~10倍)、更快(20 ~ 100倍),但是使用也相对复杂。

搭建Protobuf c++ vs工程

1  获取 protobuf库

   win下需自行编译,下载后编译。

Releases · protocolbuffers/protobuf · GitHub

 2  配置测试工程

上述编译成功后生成库目录,将依赖头文件、lib文件、dll文件配置到测试工程中

 

 工程配置如下:

常规\输出目录                      ..\..\build\$(PlatformToolset)\$(Platform)\$(Configuration)\

C/C++\常规\附加包含目录   ..\..\build\include

 链接器\常规\附加库目录     ..\..\build\$(PlatformToolset)\$(Platform)\lib

3   编写msgtest.proto文件

syntax="proto3";   //protobuf协议版本
package test;       //包名
message helloworld 

    int32 id = 1;       // 必选类型 
    string str = 2;     // str 
    int32 opt = 3;      //可选 
}

4  生成引用文件

执行上述编译好的protoc.exe,生成h与cpp文件

protoc.exe --cpp_out=. msgtest.proto

 

 5 应用

将生成的msgtest.pb.h与msgtest.pb.cc放入测试工程目录下,并添加到工程,写测试。

#include <iostream>
#include <fstream>
#include "msgtest.pb.h"

#pragma comment(lib,"libprotobuf.lib")
#pragma comment(lib,"libprotoc.lib")


void test_write()
{
	test::helloworld msg1;
	msg1.set_id(101);
	msg1.set_str("hello101");
	std::fstream output("./log", std::ios::out | std::ios::trunc | std::ios::binary);
	if (!msg1.SerializeToOstream(&output))
	{
		std::cerr << "Failed to write msg." << std::endl; return;
	}
}

void test_read()
{
	test::helloworld msg2;
	{
		std::fstream input("./log", std::ios::in | std::ios::binary);
		if (!msg2.ParseFromIstream(&input)) {
			std::cerr << "Failed to parse address book." << std::endl;
			return;
		}
	}
	std::cout << "id:"<< msg2.id() << std::endl;
	std::cout << "str:" << msg2.str() << std::endl;
}

int main()
{
	std::cout << "hello protobuf" << std::endl;
	test_write();
	test_read();
	getchar();
	return 0;
}

6 编译运行

编译错误:无法解析的外部符号 "class google::protobuf::internal::ExplicitlyConstructed<class std::basic_string<char,struct std::char_traits,class std::allocator > >

解决:在生成的msgtest.pb.h头文件中添加 #define PROTOBUF_USE_DLLS

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值