转一篇如何用protobuf-csharp-port

先存下,省的麻烦:

Pre-requisites

Rather than reproduce all the documentation of the main Google Protocol Buffers project page, I‘ll just reference it - so please read at least the language guide before going any further. The rest of the wiki assumes you already know the basics of Protocol Buffers. Likewise, currently the project only works on Windows and .NET; when support is provided for Mono on other platforms, the documentation will be updated.

First, either grab the source or a distribution. All new development is now done in Mercurial on Google Code; the previous github repository is obsolete.

If you fetched the source version, build the code. From the build directory, run (for a Release build):

  • build Rebuild Release
  • build BuildPackage Release

This will create a directory build_output\Package containing:

  • protos directory with reference messages
  • Protoc directory containing protoc.exe. This is the native executable from the main Protocol Buffers project. It‘s always possible that other versions of protoc.exe will work with this project (it‘s just a stock build) but obviously I‘m more confident in the particular version supplied, simply because I know more about it.
  • Release directory containing all the release binaries:
    • Google.ProtocolBuffers.dll - the main library
    • Google.ProtocolBuffersList.dll - a lightweight version of the library with slightly less functionality, designed for constrained environments.
    • ProtoGen.exe - the source code generator
    • ProtoMunge.exe - tool to remove sensitive data from binary messages
    • ProtoDump.exe - tool to dump a binary message as text
    • ProtoBench.exe - tool to run performance benchmarks on binary messages

Sample application: an address book

In-keeping with the sample provided in the main project, the C# port comes with an address book application so you can see the basics of how to get going with Protocol Buffers. The code is built as part of the normal build in the source distribution, but we‘ll take it step by step here.

The .proto file

Let‘s start off with the addressbook.proto file which describes the messages. This lives in protos/tutorial in the source distribution.

package tutorial;

import "google/protobuf/csharp_options.proto";

option (google.protobuf.csharp_file_options).namespace = "Google.ProtocolBuffers.Examples.AddressBook";
option (google.protobuf.csharp_file_options).umbrella_classname = "AddressBookProtos";

option optimize_for = SPEED;

message Person {
  required string name = 1;
  required int32 id = 2;        // Unique ID number for this person.
  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;
}

// Our address book file is just one of these.
message AddressBook {
  repeated Person person = 1;
}

This is mostly just the same as the file in the main Protocol Buffers project, but there are a few tweaks:

  • The Java options have been removed, just for simplicity. (If you want a single .proto file which can generate Java code and C# code, you just need the Java options and the C# options. They don‘t conflict at all.)
  • There‘s an import of google/protobuf/csharp_options.proto in order to use the C#-specific option extensions.
  • There are two C#-specific options specified:
    • The name of the class containing the descriptor representing the overall .proto file. (This is called the "umbrella" class.) The generated source file is also named after this class. In this case we‘re using AddressBookProtos.
    • The namespace to use for all the generated classes. For the address book application we‘re using Google.ProtocolBuffers.Examples.AddressBook.
  • The optimization flag is set to optimize for speed instead of code size. This does generate quite a lot more code, but it‘s a lot faster.

Other options are available - see DescriptorOptions for details.

Generating the source code

For simplicity, I would recommend copying protoc.exe from the Protoc directory into the Release directory; ProtoGen.exe can spot the existence of protoc.exe in the current directory (or in the path) and run it automatically. This is simpler than the old "two step" approach.

protogen ..\protos\tutorial\addressbook.proto
         ..\protos\google\protobuf\csharp_options.proto
         ..\protos\google\protobuf\descriptor.proto
         --proto_path=..\protos

That will create a collection of .cs files in the current directory. We only actually need AddressBookProtos.cs - the others are the dependencies (the core Protocol Buffers descriptors and the C# options). You can optionally ignore dependencies, and also specify the output directory as of version 2.3.

We‘ll look into ways of making this slightly simpler... in particular, protogen now allows you to specify C# options on the command line, rather than in the proto file.

A few words of advice

  1. Make sure that you do not use a non-ASCII encoding with your text file. The protoc.exe compiler will complain with the following message:

    tutorial/addressbook.proto:1:1: Expected top-level statement (e.g. "message").

    The best way to fix this is with Visual Studio. Open the proto file and select "File" -> "Save as...". From the save dialog click the down arrow next to     the save button and select "Save with Encoding". Select the "US-ASCII" codepage (near the bottom) and click save.

  2. It‘s often easiest keep all your proto files in a single directory tree. This allows to omit the --proto_path option by running protoc.exe from the top of     the this directory tree. Always keep the ‘google/protobuf/*.proto‘ files available so that you can import them to specify options, or use the options     through protogen.

  3.Unlike a programming language like C# it is usually expected that your proto file will specify numerous messages, not one. Name your proto files     based on the namespace, not the message. Create proto files only as often as you would create a new namespace to organize those classes.

Example Usage

The following example uses the classes generated by the above proto file to perform these operations:

  1. Create a builder to construct a Person message
  2. Sets the field values of the builder
  3. Creates the Person immutable message class
  4. Writes the Person to a stream
  5. Creates a new Person from the bytes written
  6. Adds the Person to a new AddressBook
  7. Saves the AddressBook to bytes and recreates it
  8. Verifies the AddressBook contents

        static void Sample()
        {
            byte[] bytes;
            //Create a builder to start building a message
            Person.Builder newContact = Person.CreateBuilder();
            //Set the primitive properties
            newContact.SetId(1)
                      .SetName("Foo")
                      .SetEmail("[email protected]");
            //Now add an item to a list (repeating) field
            newContact.AddPhone(
                //Create the child message inline
                Person.Types.PhoneNumber.CreateBuilder().SetNumber("555-1212").Build()
                );
            //Now build the final message:
            Person person = newContact.Build();
            //The builder is no longer valid (at least not now, scheduled for 2.4):
            newContact = null;
            using(MemoryStream stream = new MemoryStream())
            {
                //Save the person to a stream
                person.WriteTo(stream);
                bytes = stream.ToArray();
            }
            //Create another builder, merge the byte[], and build the message:
            Person copy = Person.CreateBuilder().MergeFrom(bytes).Build();
    
            //A more streamlined approach might look like this:
            bytes = AddressBook.CreateBuilder().AddPerson(copy).Build().ToByteArray();
            //And read the address book back again
            AddressBook restored = AddressBook.CreateBuilder().MergeFrom(bytes).Build();
            //The message performs a deep-comparison on equality:
            if(restored.PersonCount != 1 || !person.Equals(restored.PersonList[0]))
                throw new ApplicationException("There is a bad person in here!");
        }
时间: 2024-10-08 19:35:00

转一篇如何用protobuf-csharp-port的相关文章

Phonegap IOS 篇 -如何用虚拟机发布APP

今天给大家介绍一下如何用windows 系统装上虚拟机后,发布IOS程序 1首先当然是安装虚拟机并配置好MAC系统了,这里推荐机器最好是有10个G以上的内存,要不会卡死你,我的机器是台式机I5,带 16G内存 ,一般跑虚拟机的时候 内存要消耗到10个G左右,非常流畅,在这里特别提醒 8,9个G的笔    记本就别玩虚拟机了 卡到想死的心都有了,有钱的可以直接上MAC笔记本,可以省掉不少麻烦 如何安装MAC虚拟机,请大家到这个网址下载各种工具 ,傻瓜教程:http://diybbs.zol.com

Netty with protobuf(二)

上一篇了解了protobuf,现在结合netty做一个例子. 关键就是配置netty的编解码器,因为netty提供了protobuf的编解码器,所以我们可以很容易的使用netty提供的编解码器使用protobuf数据交换协议进行通信.. 下面是示例代码,对于了解的netty的同学应该不难看懂.. 服务器端程序: ProtobufNettyServer.java package com.example.tutorial; import io.netty.bootstrap.ServerBootst

google protobuf学习笔记一:使用和原理

一.什么是protobuf protobuf全称Google Protocol Buffers,是google开发的的一套用于数据存储,网络通信时用于协议编解码的工具库.它和XML或者JSON差不多,也就是把某种数据结构的信息,以某种格式(XML,JSON)保存起来,protobuf与XML和JSON不同在于,protobuf是基于二进制的.主要用于数据存储.传输协议格式等场合.那既然有了XML等工具,为什么还要开发protobuf呢?主要是因为性能,包括时间开销和空间开销: 1.时间开销:XM

protobuf v3测试

谷歌最近发布了v3版本的protobuf,以前的protobuf被称之为v2,二者之间的区别其特点见我上一篇blog<protobuf一些注意事项>. 个人以为v3要比v2好处就在于:简洁,且二者的新版本都共同支持了新的数据类型:map.相比v2,它去掉了required等选项,只保留了repeated选项,还添加了时间等比较常用的数据类型(当然暂时还没有实现)等等.唯一的缺点就是,v3还没有发布beta版,目前的版本是protobuf-3.0.0-alpha-1. 为了测试v3对v2的兼容性

【转】C# 串口操作系列(2) -- 入门篇,为什么我的串口程序在关闭串口时候会死锁

第一篇文章我相信很多人不看都能做的出来,但是,用过微软SerialPort类的人,都遇到过这个尴尬,关闭串口的时候会让软件死锁.天哪,我可不是武断,算了.不要太绝对了.99.9%的人吧,都遇到过这个问题.我想只有一半的人真的解决了.另外一半的人就睁只眼闭只眼阿弥佗佛希望不要在客户那里出现这问题了. 你看到我的文章,就放心吧,这问题有救了.我们先回顾一下上一篇中的代码 [c-sharp] view plaincopy void comm_DataReceived(object sender, Se

C# 串口操作系列(2) -- 入门篇,为什么我的串口程序在关闭串口时候会死锁 ?

C# 串口操作系列(2) -- 入门篇,为什么我的串口程序在关闭串口时候会死锁 ? 标签: c#objectuibyte通讯.net 2010-05-19 08:43 55212人阅读 评论(188) 收藏 举报  分类: 通讯类库设计(4)  版权声明:本文为博主原创文章,未经博主允许不得转载. 第一篇文章我相信很多人不看都能做的出来,但是,用过微软SerialPort类的人,都遇到过这个尴尬,关闭串口的时候会让软件死锁.天哪,我可不是武断,算了.不要太绝对了.99.9%的人吧,都遇到过这个问

Python 模块大全

1 算法 1.1 字符串处理 re 正则表达式的标准库. StringIO / cStringIO 以读写文件的方式来操作字符串(有点类似于内存文件). cStringIO 是 C 语言实现的,提供高性能:而 StringIO 是 Python 实现的,提供 Unicode 兼容性. chardet chardet 可以猜测任意一段文本的字符集编码.对于编码类型未知的文本,它会很有用. chardet 既可以作为模块来使用,也可以作为命令行工具来使用. 代码示例 import chardet p

Google Protocol Buffers 快速入门(带生成C#源码的方法)

Google Protocol Buffers是google出品的一个协议生成工具,特点就是跨平台,效率高,速度快,对我们自己的程序定义和使用私有协议很有帮助. Protocol Buffers入门:1.去 http://code.google.com/p/protobuf/downloads/list 下载一个源代码包和一个已编译好的二进制包2.找一个Proto示例代码,使用命令 protoc -I=$SRC_DIR --java_out=$DST_DIR $SRC_DIR/addressbo

娱乐往事,年初捡到1G PAR,平淡的日子泛起波澜

常听说这样的故事 垃圾佬捡到蓝牙键盘,于是配了一台上万的电脑 垃圾佬捡到机箱,于是配了一台带遥控的HTPC 垃圾佬捡到假NAS,于是组了20+T的RAID 而我,不是垃圾佬,更没有捡到过U盘(当然就从来没有买过松江斐讯啦),对突如其来的PAR,我是拒绝的,但是--众所周知,春节前的疫情已经很严峻,所以大家都能不出门都不出门了,亲友团聚也省略了,游乐园关门,逛超市带起了口罩,每天数字都在更新,在关心时政之余,鼓励不出门措施也在渐渐累积,甚至曾经付费的1080p降级高清突然出现了半个多月的免费期,这