`
hideto
  • 浏览: 2667070 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

protobuf示例

    博客分类:
  • C++
阅读更多
1, 下载compiler和源代码
http://code.google.com/p/protobuf/downloads/

build protobuf:
./configure
make
make check
make install


2, 创建一个addressbook.proto
package tutorial;

message Person {
  required string name = 1;
  required int32 id = 2;
  optional string email = 3;
  
  enum PhoneType {
    MOBILE = 0;
    HOME = 1;
    WORK = 2;
  }
  
  message PhoneNumber {
    required string number = 1;
    optional PhoneType type = 2 [default = HOME];
  }
  
  repeated PhoneNumber phone = 4; 
}

message AddressBook {
  repeated Person person = 1;
}


3, 生成C++的stub
protoc --cpp_out=. ./addressbook.proto

运行上面的命令将生成addressbook.pb.h和addressbook.pb.cc

4, 写
// write.cc
#include <iostream>
#include <fstream>
#include <string>
#include "addressbook.pb.h"
using namespace std;

void PromptForAddress(tutorial::Person* person) {
	cout << "Enter person ID number: ";
	int id;
	cin >> id;
	person->set_id(id);
	cin.ignore(256, '\n');

	cout << "Enter name: ";
	getline(cin, *person->mutable_name());

	cout << "Enter email address (blank for none): ";
	string email;
	getline(cin, email);
	if (!email.empty()) {
		person->set_email(email);
	}

	while(true) {
		cout << "Enter a phone number (or leave blank to finish):";
		string number;
		getline(cin, number);
		if (number.empty()) {
			break;
		}

		tutorial::Person::PhoneNumber *phone_number = person->add_phone();
		phone_number->set_number(number);

		cout << "Is this a mobile, home, or work phone?";
		string type;
		getline(cin, type);
		if (type == "mobile") {
			phone_number->set_type(tutorial::Person::MOBILE);
		} else if (type == "home") {
			phone_number->set_type(tutorial::Person::HOME);
		} else {
			cout << "Unknown phone type. Using default." << endl;
		}
	}
}

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

	if(argc != 2) {
		cerr << "Usage: " << argv[0] << " ADDRESS_BOOK_FILE" << endl;
		return -1;
	}

	tutorial::AddressBook address_book;

	{
		fstream input(argv[1], ios::in | ios::binary);
		if (!input) {
			cout << argv[1] << ": File not found. Creating a new file." << endl;
		} else if (!address_book.ParseFromIstream(&input)) {
			cerr << "Failed to parse address book." << endl;
			return -1;
		}
	}

	PromptForAddress(address_book.add_person());
	{
		fstream output(argv[1], ios::out | ios::trunc | ios::binary);
		if (!address_book.SerializeToOstream(&output)) {
			cerr << "Failed to write address book." << endl;
			return -1;
		}
	}

	google::protobuf::ShutdownProtobufLibrary();

	return 0;
}

编译生成write.exe
注意:
需要将protobuf的源码以及lib加到编译的PATH中

向文件写数据:
write ADDRESS_BOOK_FILE

Enter person ID number: 123
Enter name: Hideto
Enter email address (blank for none): hideto.bj@gmail.com
Enter a phone number (or leave blank to finish):159xxxxxxxx
Is this a mobile, home, or work phone?mobile
Enter a phone number (or leave blank to finish):

write ADDRESS_BOOK_FILE
// ....


5, 读
// read.cc
#include <iostream>
#include <fstream>
#include <string>
#include "addressbook.pb.h"
using namespace std;

void ListPeople(const tutorial::AddressBook& address_book) {
    for (int i = 0; i < address_book.person_size(); i++) {
        const tutorial::Person& person = address_book.person(i);

        cout << "Person ID: " << person.id() << endl;
        cout << "Name: " << person.name() << endl;
        if(person.has_email()) {
            cout << "E-mail address: " << person.email() << endl;
        }

        for (int j = 0; j < person.phone_size(); j++) {
            const tutorial::Person::PhoneNumber& phone_number = person.phone(j);

            switch (phone_number.type()) {
                case tutorial::Person::MOBILE:
                    cout << "Mobile phone #: ";
                    break;
                case tutorial::Person::HOME:
                    cout << "Home phone #: ";
                    break;
                case tutorial::Person::WORK:
                    cout << "Work phone #: ";
                    break;
            }
            cout << phone_number.number() << endl;
        }
    }
}

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

    if (argc != 2) {
        cerr << "Usage: " << argv[0] << "ADDRESS_BOOK_FILE" << endl;
        return -1;
    }

    tutorial::AddressBook address_book;
    {
        fstream input(argv[1], ios::in | ios::binary);
        if (!address_book.ParseFromIstream(&input)) {
            cerr << "Failed to parse address book." << endl;
            return -1;
        }
    }

    ListPeople(address_book);

    google::protobuf::ShutdownProtobufLibrary();

    return 0;
}

编译生成read.exe
从文件读数据:
read ADDRESS_BOOK_FILE

// 以下为输出
Person ID: 123
Name: Hideto
E-mail address: hideto.bj@gmail.com
Mobile phone #: 159xxxxxxxx
Person ID: 456
Name: chuang
E-mail address: chuang@freewheel.tv
Home phone #: 22222222
Person ID: 1231231
Name: asdfadsf
E-mail address: fadsfdsf@dasfads.com
Mobile phone #: 12321321321
Home phone #: 123432432


6, Ruby的protobuf库
http://code.google.com/p/ruby-protobuf/
安装:
gem install ruby_protobuf

生成ruby的stub:
rprotoc addressbook.proto

从文件读数据:
# read.rb
require 'addressbook.pb.rb'

def list_people(address_book)
  address_book.person.each do | p |
    p "Person ID: #{p.id}"
    p "Name: #{p.name}"
    p "E-mail: #{p.email}" unless p.email.empty?
    p.phone.each do |phone|
      case phone.type
      when Tutorial::Person::PhoneType::MOBILE
        print "Mobile phone #: "
      when Tutorial::Person::PhoneType::HOME
        print "Home phone #: "
      when Tutorial::Person::PhoneType::WORK
        print "Work phone #: "
      end
      p phone.number
    end
  end
end

address_book = Tutorial::AddressBook.new
address_book.parse_from_file ARGV[0]

list_people address_book

运行:
ruby read.rb 'D:\cpp-projects\pb\bin\Release\ADDRESS_BOOK_FILE'

// 输出
"Person ID: 123"
"Name: Hideto"
"E-mail: hideto.bj@gmail.com"
Mobile phone #: "159xxxxxxxx"
"Person ID: 456"
"Name: chuang"
"E-mail: chuang@freewheel.tv"
Home phone #: "22222222"
"Person ID: 1231231"
"Name: asdfadsf"
"E-mail: fadsfdsf@dasfads.com"
Mobile phone #: "12321321321"
Home phone #: "123432432"
分享到:
评论

相关推荐

    protobuf示例参考

    标题“protobuf示例参考”指的是关于protobuf实际操作的指导,可能包含一系列的实例,展示了如何在不同的编程语言中使用protobuf。下面我们将深入探讨protobuf的核心概念、工作原理及常见应用场景。 1. **protobuf...

    protobuf使用示例

    **protobuf使用示例** protobuf(Protocol Buffers)是Google开发的一种数据序列化协议,它可以将结构化的数据序列化,可用于数据存储、通信协议等方面。它提供了比XML更小、更快、更简单的方式来让结构化数据进行...

    protobuf java 工程示例

    标题中的“protobuf java 工程示例”表明我们将探讨Google的Protocol Buffers(简称protobuf)在Java编程语言中的实际应用。Protocol Buffers是一种高效的数据序列化协议,它允许开发者定义数据结构,然后生成能够在...

    protobuf-example:protobuf 示例

    Protobuf run demo go run main.go # js -&gt; browser open : 127.0.0.1:51002 # go -&gt; go test -v ./go Protobuf是一种用于序列化结构化数据的灵活,高效,自动化的机制。 能够将结构化数据序列化,可用于数据存储,...

    protobuf for unity 在unity中使用protobuf工程示例

    protobuf for unity 在unity中使用protobuf工程示例,数据的序列化和反序列化工程示例

    netty http protobuf

    总结来说,Netty HTTP Protobuf示例展示了如何利用这三个强大的工具来构建一个高效、可靠的网络通信系统。通过Netty实现HTTP服务器和客户端,利用Protobuf进行高效的数据序列化和反序列化,可以极大地提升应用程序的...

    android netty cli +probuf示例

    总结来说,“android netty cli +protobuf示例”展示了如何在Android客户端利用Netty的异步网络通信能力和Protobuf的数据序列化特性,构建一个高效的即时通讯系统。这个示例涵盖了从消息定义到网络通信的全过程,...

    protobuf文档示例与编译器.zip

    8. **示例代码**:示例代码通常会涵盖基本的消息定义、序列化、反序列化,以及如何在服务端和客户端使用protobuf进行通信。 9. **生态和工具**:protobuf有一个丰富的生态系统,包括各种语言的库、IDE插件、代码...

    2.Protobuf编译使用说明1

    本文将详细介绍如何在Windows 7 64位环境下,利用CMake和Visual Studio 2015对Protobuf进行编译,并安装Visual Studio的protobuf编辑插件,以及编写和测试简单的protobuf示例。 1. **编译环境配置**: - 操作系统...

    PHP调用protobuf的rpc接口示例和说明

    本示例主要探讨如何在PHP中调用使用protobuf编译的RPC接口。 首先,了解protobuf的基本概念。protobuf是一种语言无关、平台无关的序列化框架,它可以将结构化的数据序列化为二进制流,以便在网络间传输或者存储到...

    protobuf测试文件

    这通常涉及到编译或运行一个特定的protobuf示例程序,以确保系统上的protobuf库和相关工具能够正常工作。这个压缩包文件“Protocol-Buffer-Test”很可能包含了一个或多个测试用例,比如.proto文件(protobuf的接口...

    protobuf的protoc.exe和jar

    **一个简单的protobuf示例** 假设我们有一个名为`person.proto`的.proto文件,内容如下: ```protobuf syntax = "proto3"; message Person { string name = 1; int32 id = 2; string email = 3; } ``` 使用...

    prototest&install.rar

    描述中提到,这个压缩包包含了一个基于Visual Studio 2019(VS2019)的protobuf示例工程,这个工程可以帮助开发者理解和学习如何在C++项目中使用protobuf。"Install"文件夹则包含了protobuf编译后的库文件(lib)和...

    protobuf_android_sample,使用protobuf的示例android应用程序.zip

    项目“protobuf_android_sample”应该包含了Android Studio工程文件、protobuf定义文件(.proto)、生成的Java源代码以及相关的示例代码,展示了如何在Android应用中实际使用protobuf。开发者可能还提供了一些测试...

    eclipse protobuf 安装配置示例

    标题 "eclipse protobuf 安装配置示例" 涉及到的是在Eclipse集成开发环境中使用Protocol Buffers(简称protobuf)的相关知识。Protocol Buffers是Google推出的一种数据序列化协议,它允许开发者定义数据结构,然后...

    protobuf 使用简单示例

    Protocol Buffers是Google公司开发的一种数据描述语言,类似于XML能够将结构化数据序列化,可用于数据存储、通信协议等方面。它不依赖于语言和平台并且可扩展性极强。现阶段官方支持C++、JAVA、Python等三种编程语言...

    netty基于protobuf的简单示例

    在本示例中,我们将深入探讨如何利用 Netty 和 Google 的 Protocol Buffers(protobuf)来构建一个简单的服务端和客户端通信系统。 Protocol Buffers 是 Google 提供的一种数据序列化协议,它可以将结构化数据序列...

    Windows环境使用google protobuf实现简单的例子

    标题中的“Windows环境使用google protobuf实现简单的例子”指的是在Windows操作系统下,利用Visual Studio (VS) 2010开发环境,结合Google的Protocol Buffers(protobuf)版本2.5.0进行简单应用的教程。protobuf是...

Global site tag (gtag.js) - Google Analytics