一. 獲取Protocol Buffer
1.1 獲得源碼
-
Git clone之:git clone https://github.com/google/protobuf.git
-
或者直接下載release版本:https://github.com/google/protobuf/releases
-
本例選擇從release下載3.7.0版本
-
下載並解壓到目錄: D:\wzx\protobuf\protobuf-3.7.0
1.2 編譯protoc.exe(Windows平台)
准備工具: VS2017(包含C++模塊),
提取碼:jwa7
1.打開cmake目錄,運行cmakegui:
D:\wzx\protobuf\cmake-3.14.0-win64-x64\bin\cmake-gui.exe
2.配置選項:
-
Source Code目錄: D:/wzx/protobuf/protobuf-3.7.0/cmake
-
build the binaries目錄:D:/wzx/protobuf/cmake-3.14.0-win64-x64/bin/protobuf-build
-
菜單欄Tools->configure,選擇generator:
-
本例使用VS2017 64位版本,所以選擇:Visual Studio 15 2017
-
4.點擊finish,結果如下圖:
5.將列表中的protobuf_BUILD_SHARED_LIBS勾上, 然后generator。
查看D:\wzx\protobuf\cmake-3.14.0-win64-x64\bin\protobuf-build目錄,你會發現生成了一個VS工程。
3.用VS2015 編譯protobuf-build工程:
-
雙擊打開D:\wzx\protobuf\cmake-3.14.0-win64-x64\bin\protobuf-build\protobuf.sln
-
我們選擇release來生成解決方案:
然后等待編譯完成。。。速度有點慢,大概要花幾分鍾。
3.最后編譯成功:
4.進入D:\wzx\protobuf\cmake-3.14.0-win64-x64\bin\protobuf-build\Release, 即可看到編譯的結果.
二、簡單使用
1.創建一個xxx.proto文件,至於這個文件怎么寫,請看鏈接
http://www.cnblogs.com/dkblog/archive/2012/03/27/2419010.html
2.利用D:\wzx\protobuf\cmake-3.14.0-win64-x64\bin\protobuf-build\Release 目錄下的protoc.exe運行以下命令生成.cc和.h文件
protoc -I=$SRC_DIR --cpp_out=$DST_DIR $SRC_DIR/xxx.proto
$SRC_DIR:源地址 D:\wzx\protobuf\cmake-3.14.0-win64-x64\bin\protobuf-build\Release
$DST_DIR:目的地址 D:\wzx\protobuf\cmake-3.14.0-win64-x64\bin\protobuf-build\Release\h
$SRC_DIR:源地址 D:\wzx\protobuf\cmake-3.14.0-win64-x64\bin\protobuf-build\Release
3.執行之后h文件夾下面出現my.pb.cc和my.pb.h兩個文件
4.把my.pb.cc、my.pb.h和libprotobuf.dll、libprotoc.dll、libprotobuf.lib、libprotoc.lib兩個動態庫添加到vs工程即可
期間遇到了幾個問題:
1.是否忘記了向源中添加“#include "pch.h"”?
解決方案:添加頭文件的引用 “#include "pch.h“,注意一定要添加到所有頭文件最上面
2.無法解析的外部符號 "class google::protobuf::internal::ExplicitlyConstructed<class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > > google::protobuf::internal::fixed_address_empty_string
解決方案:在添加的pch.h中添加#define PROTOBUF_USE_DLLS宏定義
3.使用set_str(string)設置屬性和SerializeToString()轉化字符串的時候一直報錯,原因是使用的是release版本的dll,在debug()模式下會產生錯誤。建議在調試的時候要同時編譯一個debug的dll版本進行調試。奇怪的時候我之前一直用的mingw編譯的靜態庫版本.a在debug和release模式下面結果一直保持一致,沒有出錯。
4.屬性設置:選擇MT或者MTD
4.inet_ntoa函數出現:'inet_ntoa': Use inet_ntop() or InetNtop() instead or define
解決方案:文件的屬性頁----->c/c++--->常規,將SDL檢查改為否
5.dll動態庫放到工程目錄或者exe目錄下
6.代碼編寫
proto格式
message SearchRequest { required string query = 1; optional int32 page_number = 2; optional int32 result_per_page = 3; }
通過socket實現的Tcp傳輸完成client到server的傳輸內容的序列化和反序列化
//client
//使用protobuf *序列化 SearchRequest* search = new SearchRequest; search->set_page_number(1); search->set_result_per_page(10); int buffsize = search->ByteSize(); void* buff = malloc(buffsize); search->SerializeToArray(buff, buffsize); //發送 send(sclient, (char*)buff, strlen((char*)buff), 0);
//server
//protobuf *反序列化 SearchRequest* request = new SearchRequest; request->ParseFromArray((void*)revData, ret); int pageNum = request->page_number(); int perPage = request->result_per_page();