protocol buffer动态创建库
更新日期:
关于protocol buffer消息的动态创建在之前的博客中已经有大概的介绍了,按照这种原理我编写了一个c++的库,它可以动态的创建protocol buffer结构体,并最终生成.proto文件。
下面简单介绍一下这个库的使用:
bool newproto(const char* name, const char* version=”proto3”);
创建.proto文件 name文件名 version版本
bool addmessage(const char* name);
创建protocol buffer消息类 name消息名
bool addfield(const char* messagename, const char* fieldname, int number, int itype, int label=LABEL_OPTIONAL, const char* fmname=NULL);
给指定消息体添加成员 消息体名称 成员名称 标号 数据类型 lable类型 如果itype=TYPE_MESSAGE,fmname指定filed的消息类型名称
bool addmapfield(const char* messagename, const char* fieldname, int number, int keytype, int valtype, const char* fmname=NULL);
给指定消息体添加map类型成员 消息体名称 成员名称 标号 key数据类型 value数据类型 如果valtype=TYPE_MESSAGE,fmname指定map中value的消息类型名称
bool save(const char* path=”./“);
保存生成的.proto文件
其中数据类型定义、label类型定义与protocol buffer源码中的定义一致1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37enum Type {
TYPE_DOUBLE = 1, // double, exactly eight bytes on the wire.
TYPE_FLOAT = 2, // float, exactly four bytes on the wire.
TYPE_INT64 = 3, // int64, varint on the wire. Negative numbers
// take 10 bytes. Use TYPE_SINT64 if negative
// values are likely.
TYPE_UINT64 = 4, // uint64, varint on the wire.
TYPE_INT32 = 5, // int32, varint on the wire. Negative numbers
// take 10 bytes. Use TYPE_SINT32 if negative
// values are likely.
TYPE_FIXED64 = 6, // uint64, exactly eight bytes on the wire.
TYPE_FIXED32 = 7, // uint32, exactly four bytes on the wire.
TYPE_BOOL = 8, // bool, varint on the wire.
TYPE_STRING = 9, // UTF-8 text.
TYPE_GROUP = 10, // Tag-delimited message. Deprecated.
TYPE_MESSAGE = 11, // Length-delimited message.
TYPE_BYTES = 12, // Arbitrary byte array.
TYPE_UINT32 = 13, // uint32, varint on the wire
TYPE_ENUM = 14, // Enum, varint on the wire
TYPE_SFIXED32 = 15, // int32, exactly four bytes on the wire
TYPE_SFIXED64 = 16, // int64, exactly eight bytes on the wire
TYPE_SINT32 = 17, // int32, ZigZag-encoded varint on the wire
TYPE_SINT64 = 18, // int64, ZigZag-encoded varint on the wire
MAX_TYPE = 18, // Constant useful for defining lookup tables
// indexed by Type.
};
enum Label {
LABEL_OPTIONAL = 1, // optional
LABEL_REQUIRED = 2, // required
LABEL_REPEATED = 3, // repeated
MAX_LABEL = 3, // Constant useful for defining lookup tables
// indexed by Label.
};
附源码
https://github.com/sstask/googleprotobufmore/blob/master/gpbcreator.h
https://github.com/sstask/googleprotobufmore/blob/master/gpbcreator.cpp