window 10 Protocol v3.3.0 版本編譯即使用

1.下載cmake:
https://cmake.org/download/
cmake-3.9.0-win64-x64.msi 最新版本

  1. 下載protobuf 3.3 版本
    https://github.com/google/protobuf/releases

  2. 安裝Cmake

  3. 這裏寫圖片描述

    注意:這裏一定要選擇你機器安裝的版本,否則報以下錯誤
    錯誤1:CMake編譯時出現“error in configuration process project files may be invalid”
    錯誤2:No CMAKE_CXX_COMPILER could be found.

    5.這裏寫圖片描述

6.編譯protobuf工程
在debug目錄下生成三個文件 libprotobufd.lib,libprotobuf-lited.lib,libprotocd.lib

  1. proto 文件使用
syntax = "proto3";

message Friend {
    string name = 1;
    string number = 2;
}

message UserInfo {
  string nickname = 1;
  int32 age = 2;
  bool sex = 3;
  repeated Friend friends = 4;
  map<int32, string> skills = 5;
}
  1. 編譯proto文件的bat文件
echo on
::set DST_DIR = %~dp0
set Path=protoc.exe
%Path% --cpp_out=%~dp0 test.proto

pause
  1. 程序調用

#include "stdafx.h"
#include<iostream>

#include "test.pb.h"
#include   <map> 

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    UserInfo searchA;
    searchA.set_nickname("East.Su");
    searchA.set_sex(true);
    for (int i = 0; i < 3; i++)
    {
        Friend* f1 = searchA.add_friends();
        f1->set_name("wangqiang");
        f1->set_number("1358946656");
    }

    auto map = searchA.mutable_skills();
    int key = 1;
    string val = "skill1";  
    (*map)[key] = val;

    key = 2;
    val = "skill2";
    (*map)[key] = val;


    searchA.SerializeAsString();

    UserInfo* searchB = new UserInfo();
    searchB->ParseFromString(searchA.SerializeAsString());

    cout << "nickname = " << searchB->nickname();

    // 數組的使用
    int size = searchB->friends_size();
    for (int i = 0; i<size; i++)
    {
        Friend tFriend = searchB->friends(i);
        string name = tFriend.name();
        string number = tFriend.number();
        cout << "frined: " << name << " = " << number << endl;
    }
    //map是的使用
    searchB->mutable_skills();
    auto pMapB = searchB->mutable_skills();
    google::protobuf::Map<google::protobuf::int32, std::string> * mapB = pMapB;
    if (mapB->size() > 0)
    {
        google::protobuf::Map<google::protobuf::int32, std::string>::iterator   it = mapB->begin();
        for (; it != mapB->end(); ++it)
        {
            cout << "skill: " << it->first << " = " << it->second << endl;
        }

    }

    getchar();
    return 0;
}

protobuf 3.3.0 any的使用:

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