简介:
1.生成vs工程
打开cmake:
选择protobuf下的cmake路径为源码路径,新建文件夹protobuf_win为生成路径。
点击Configure弹出选择vs版本的对话框
2.编译protobuf
打开vs工程,分别编译 libprotobuf和protoc这两个项目:生成libprotobufd.lib、libprotocd.lib和protoc.exe
5.生成***.cc和****.h文件
protobuf使用需要先把消息定义好,然后编译成自己的API,加入到自己的工程中使用。
(1)先编写myproto.proto文件: https://www.ibm.com/developerworks/cn/linux/l-cn-gpb/
syntax = “proto2”;
package mypb;
message helloworld
{
required int32 id = 1;
required string str = 2;
optional int32 opt=3;
}
package 名字叫做 mypb,定义了一个消息 helloworld,该消息有三个成员,类型为 int32 的 id,另一个为类型为 string 的成员 str。opt 是一个可选的成员,即消息中可以不包含该成员。
(2)编译myproto.proto文件:
可以使用dos窗口,进入到当前目录,执行:
–cpp_out是输出路径(./为当前路径),其他选项可以使用protoc --help查看
生成文件如下:
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include "myproto.pb.h"
int main(void)
{
//消息封装
mypb::helloworld in_msg;
{
in_msg.set_id(888);
in_msg.set_str("helloworld");
std::fstream output("./hello.log", std::ios::out | std::ios::trunc | std::ios::binary);
if (!in_msg.SerializeToOstream(&output)) {
std::cerr << "failed to serialize in_msg" << std::endl;
return -1;
}
}
//消息解析
mypb::helloworld out_msg;
{
std::fstream input("./hello.log", std::ios::in | std::ios::binary);
if (!out_msg.ParseFromIstream(&input)) {
std::cerr << "failed to parse" << std::endl;
return -1;
}
std::cout << out_msg.id() << std::endl;
std::cout << out_msg.str() << std::endl;
}
getchar();
return 0;
}