windows C++編譯使用protobuf

1、源碼下載

下載地址:https://github.com/protocolbuffers/protobuf/releases,目前最新版本爲:v3.11.4

2、使用CMake生成VS工程

1)解壓protobuf-cpp-3.11.4.zip,我的解壓路徑爲E:\tools\protobuf\protobuf-3.11.4

2)打開cmake

源碼路徑E:\tools\protobuf\protobuf-3.11.4\cmake

生成路徑E:\tools\protobuf\protobuf-3.11.4\cmake\vs2015_x64_build(編譯vs2015編譯器的x64版本)

3、編譯protobuf

1)使用vs2015打開工程文件protobuf.sln


2)編譯libprotobufprotoc工程的Debug和Release平臺的x86和x64版本

3)編譯生成文件

libprotobufd.lib(Debug版)、libprotobuf.lib(Release版)、protoc.exe(編譯*.proto文件)

4、生成***.pb.h和***.pb.cc文件

1)編寫TestProtobuf.proto文件

syntax = "proto3";


message TestRequestInfo{
  bytes Method   = 1;
  bytes Url      = 2;
  bytes Body    = 3;
  bytes BodyType = 4;
  sint32 TimeOut  = 5;
}

message TestResponseInfo{
  bool  code = 1;
  bytes result = 2;
}

2)編譯TestProtobuf.proto文件,在protoc.exe目錄下打開命令行並執行:protoc.exe --cpp_out=./ TestProtobuf.proto

--cpp_out是文件輸出路徑(./爲當前路徑),其他選項可以使用protoc --help查看

3)文件生成,生成的文件需要添加到項目工程中

5、使用範例

1)新建vs2015控制檯應用程序,工程名:TestProtoBuf

2)將生成的TestProtobuf.pb.hTestProtobuf.pb.cc拷貝到工程路徑下,並添加到項目文件中

3)將E:\tools\protobuf\protobuf-3.11.4\src路徑下的google目錄整個拷貝到工程路徑下

4)將google添加到工程中,TestProtobuf.pb.h會引用google目錄下的文件

5)將libprotobufd.lib(Debug版)libprotobuf.lib(Release版)拷貝到工程指定目錄下,並在工程中引用

6)測試代碼

// TestProtoBuf.cpp : 定義控制檯應用程序的入口點。
//

#include "stdafx.h"
#include "TestProtobuf.pb.h"
#include <fstream>
#include <fcntl.h>
#include <io.h>
#include <string>
using namespace std;

int main()
{
	int fd_reuest = _open("./test.log", O_CREAT | _O_BINARY | _O_TRUNC | O_RDWR, 0644);
	if (fd_reuest == -1)
	{
		printf("打開文件test.log失敗\n");
		exit(1);
	}
	printf("打開文件test.log成功\n");

	TestRequestInfo requestInfo;
	requestInfo.set_method("post");
	requestInfo.set_url("127.0.0.1:8080");
	requestInfo.set_body("<request/>你好</request>");
	requestInfo.set_bodytype("text");
	requestInfo.set_timeout(30);
	if (!requestInfo.SerializeToFileDescriptor(fd_reuest))
	{
		printf("序列化文件test.log失敗\n");
		_close(fd_reuest);
		exit(1);
	}
	printf("序列化文件test.log成功\n");
	_close(fd_reuest);

	int fd_response = _open("./test.log", _O_RDONLY | _O_BINARY, 0644);
	if (fd_response == -1)
	{
		printf("打開文件test.log失敗2\n");
		exit(1);
	}
	printf("打開文件test.log成功2\n");

	TestRequestInfo requestInfo02;
	if (!requestInfo02.ParseFromFileDescriptor(fd_response))
	{
		printf("反序列化文件test.log失敗\n");
		_close(fd_response);
		exit(1);
	}
	printf("反序列化文件test.log成功\n");
	_close(fd_response);

	string strMethod = requestInfo02.method();
	string strUrl = requestInfo02.url();
	string strBody = requestInfo02.body();
	string strBodyType = requestInfo02.bodytype();
	int time = requestInfo02.timeout();

	printf("Method:%s\nUrl:%s\nBody:%s\nBodyType:%s\nTimeOut:%d\n", strMethod.c_str(), strUrl.c_str(), strBody.c_str(), strBodyType.c_str(), time);

	system("pause");
    return 0;
}

7)編譯工程並運行

8)在程序目錄下也生成了test.log文件

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章