Protobuf使用(C++)

一、protobuf编译

[下载地址](https://github.com/protocolbuffers/protobuf/releases)

在这里插入图片描述
PS:C++下载的protobuf-cpp-3.11.4.zip

1.1、设定生成项目属性

在这里插入图片描述

1.2、生成动态库

在这里插入图片描述

1.3、生成动态库

VS直接打开生成的工程,编译运行(需要那么一丢丢时间)

二、protobuf小试牛刀

2.1、创建win32控制台程序

2.2、编写person.proto

syntax = "proto3";

package tutorial;

message Person {
  int32 id = 1;
  string name = 2;
  string email = 3;
}

message PersonList {
	repeated Person persons = 1;
}

2.3、编译person.proto

protoc --cpp_out=./ *.proto

-cpp_out:编译C++源文件

2.4、source.cpp

#include <iostream>
#include <string>
#include <sstream>
#include <map>

#include "person.pb.h"


// set the person's info
void SetPersonInfo(const tutorial::Person& infoPerson, tutorial::Person* pPerson)
{
    pPerson->set_id(infoPerson.id());
    pPerson->set_name(infoPerson.name());
    pPerson->set_email(infoPerson.email());
}

// print the persons
void ListAllPerson(const tutorial::PersonList& listPerson)
{
    for (int i = 0; i < listPerson.persons_size(); i++) {
        const tutorial::Person& person = listPerson.persons(i);
        std::cout << "ID: " << person.id() << std::endl;
        std::cout << "name: " << person.name() << std::endl;
        std::cout << "e-mail: " << person.email() << std::endl;
        std::cout << "----------------------------------------\n";
    }
}

int main(int argc, char* argv[])
{
    GOOGLE_PROTOBUF_VERIFY_VERSION;

    tutorial::Person person;
    person.set_id(666);
    person.set_name("Mark");
    person.set_email("[email protected]");

    // serialize to io-stream
    std::stringstream ss;
    person.SerializeToOstream(&ss);
    std::string strData = ss.str();
    std::cout << "Data:" << strData << "\n";
    // deserialize from io-stream
    if (!person.ParseFromIstream(&ss)) {
        std::cerr << "Failed to parse person.pb." << std::endl;
        return -1;
    }
    std::cout << "ID: " << person.id() << std::endl;
    std::cout << "name: " << person.name() << std::endl;
    std::cout << "e-mail: " << person.email() << std::endl;

    // list data
    tutorial::PersonList listPerson;
    SetPersonInfo(person, listPerson.add_persons());

    tutorial::Person person1;
    person1.set_id(8468);
    person1.set_name("Test");
    person1.set_email("[email protected]");
    SetPersonInfo(person1, listPerson.add_persons());

    // serialize to io-stream
    std::stringstream ssList;
    listPerson.SerializeToOstream(&ssList);
    std::cout << "List:" << ssList.str() << "\n";
    std::cout << "--------------------Deserialize------------------\n";
    tutorial::PersonList listDeserialize;
    listDeserialize.ParseFromIstream(&ssList);
    ListAllPerson(listDeserialize);

    std::cout << "\nFinished\n";
    getchar();
    return 0;
}

2.5、运行截图

在这里插入图片描述

发布了35 篇原创文章 · 获赞 2 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/Wite_Chen/article/details/105647423