标签:flatbuffers golang idl 序列化 go语言
试用了下FlatBuffers,把一些东东记录一下。
FlatBuffers 官网: http://google.github.io/flatbuffers/md__go_usage.html
它支持生成Go语言相关的东西,总的使用步骤如下:
3. 在Go工程中安装FlatBuffers的Go支持包,就可以在代码直接使用了.
再详细说说IDL的一些语法。先上一份.fbs的例子:
// example IDL file namespace MyGame; attribute "priority"; enum Color : byte { Red = 1, Green, Blue } ///union Any { Monster, Weapon, Pickup } //union Any { Monster} union Any { Monster, Weapon} struct Vec3 { x:float; y:float; z:float; } /// 注释 table Monster { pos:Vec3; mana:short = 150; hp:short = 100; name:string; friendly:bool = false (deprecated, priority: 1); inventory:[ubyte]; color:Color = Blue; test:Any; } table Weapon { pos:Vec3; mana:short = 150; } root_type Monster; root_type Weapon;依上面的IDL作例子来说明一下.
const ( AnyNONE = 0 AnyMonster = 1 AnyWeapon = 2 )可以看到相当于一个enum类型。
/// 加id指定生成顺序 table Monster { pos:Vec3 (id: 0); mana:short = 150 (id: 3); hp:short = 100 (id: 1); name:string (id: 2); //friendly:bool = false (deprecated, priority: 1); friendly:bool = false (deprecated,id: 4); //friendly:bool = false (priority: 1); inventory:[ubyte] (id: 6); color:Color = Blue (id: 5); test:Any (id: 8); }
依此为例,会按id指定顺序生成相关函数.
注意:
如有加id,则table中所有字段都要加id才可通过
对于Any,可以看到id为8,而不是按顺序来的7.原来是它会生成:
func (rcv *Monster) TestType() byte {}
func (rcv *Monster) Test(obj *flatbuffers.Table) bool {}
即隐含一个Type的字段。所以要加1. 即union型的,其id为{}内总个数加1
使用方法:
取值:
buf, err := ioutil.ReadFile("monster.dat") offset := 0 monster := example.GetRootAsMonster(buf, offset) got := monster.Hp()直接得到即可。
builder := flatbuffers.NewBuilder(0) str := builder.CreateString("MyMonster") example.MonsterStart(builder) example.MonsterAddPos(builder, example.CreateVec3(builder, 1.0, 2.0, 3.0, 3.0, 4, 5, 6)) example.MonsterAddHp(builder, 80) example.MonsterAddName(builder, str) example.MonsterAddInventory(builder, inv) example.MonsterAddTestType(builder, 1) // example.MonsterAddTest(builder, mon2) // example.MonsterAddTest4(builder, test4s) _ = example.MonsterEnd(builder)
MAIL: xcl_168@aliyun.com
BLOG:http://blog.csdn.net/xcl168
标签:flatbuffers golang idl 序列化 go语言
原文地址:http://blog.csdn.net/xcl168/article/details/44197161