[TOC]
定義 IDL 模型文件
FlatBuffers的模型接口定義文件后綴為 .fbs
fbs 語法
基礎(chǔ)語法
語句使用 ;
結(jié)尾
結(jié)構(gòu)體使用 {}
來限定
使用 []
來指定一個(gè)自定義類型
范例
namespace com.my.event;
table Event{
touch : [Touch];
}
table Touch{
x : int(id: 0);
y : int(id: 1);
}
root_type Event;
關(guān)鍵字
關(guān)鍵字 | 描述與用途 |
---|---|
/// | FlatBuffers中用 "http:///" 來表示注釋,且此注釋會(huì)帶入到生成的源碼文件中 |
namespace | 模型目錄拗小,包結(jié)構(gòu) |
table | 模型類標(biāo)識(shí) 會(huì)生成對(duì)應(yīng)標(biāo)識(shí)的單個(gè)模型文件的類 |
bool short int float string | 默認(rèn)數(shù)據(jù)類型關(guān)鍵字 |
enum | 枚舉類數(shù)據(jù)定義 |
union | 生成一個(gè)獨(dú)立的枚舉類 |
deprecated | 指定deprecated,可以刪除掉此字段 |
priority | 設(shè)定優(yōu)先權(quán) |
root_type | 其table生成的文件中,除Table中字段會(huì)生成相關(guān)函數(shù)外會(huì)另外生成GetRootAsXXX()的函數(shù) |
required | struct的每個(gè)字段都為required,table的每個(gè)字段都默認(rèn)都是optional,但可以指定為required |
id | 設(shè)置生成指定順序侣颂,要求這個(gè)table里面全部都寫上才生效 |
include | 引入另一個(gè)fbs內(nèi)容 |
范例
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;
fbs 技巧
///直接嵌套struct
table Monster { pos:Vec3; ...}
/// 直接指定數(shù)據(jù)類型及默認(rèn)值
mana:short = 150;
/// 指定deprecated膀哲,可以刪除掉此字段
friendly:bool = false (deprecated, priority: 1);
/// 加id指定生成順序
mana:short = 150 (id: 3);
///
include "include_test1.fbs"; 形式,將其它.fbs文件嵌套進(jìn)來
如有加id,則table中所有字段都要加id才可通過
生成對(duì)應(yīng)語言的模型文件
使用 flatc
生成對(duì)應(yīng)語言的模型文件
--cpp -c Generate C++ headers for tables/structs.
--go -g Generate Go files for tables/structs.
--java -j Generate Java classes for tables/structs.
--js -s Generate JavaScript code for tables/structs.
--csharp -n Generate C# classes for tables/structs.
--python -p Generate Python files for tables/structs.
--php Generate PHP files for tables/structs.
flatc -g Test.fbs
自動(dòng)更新模型文件腳本
#!/usr/bin/env bash
rm -rf flatbuffer
mkdir -p flatbuffer/java
mkdir -p flatbuffer/go
cd flatbuffer/java
flatc -j ../SimulationEvent.fbs
cd ..
cd go
flatc -g ../SimulationEvent.fbs
更新腳本是一個(gè)范例,建議自己修改~
golang 項(xiàng)目中使用
安裝golang支持包
go get -u -v google/flatbuffers/go
golang官方使用Flatbuffers文檔 http://google.github.io/flatbuffers/index.html
或者 根據(jù)范例來使用
https://github.com/google/flatbuffers/tree/master/samples
java使用 (Android中也一樣)
引入依賴庫
dependencies {
compile 'com.github.davidmoten:flatbuffers-java:1.3.0.1'
}
按照例子使用
https://github.com/google/flatbuffers/blob/master/samples/SampleBinary.java