FlatBuffers 使用 Golang java 指引

[TOC]

定义 IDL 模型文件

FlatBuffers的模型接口定义文件后缀为 .fbs

fbs 语法

基础语法

语句使用 ; 结尾
结构体使用 {} 来限定
使用 [] 来指定一个自定义类型

范例

namespace com.my.event;
table Event{
    touch : [Touch];
}

table Touch{
    x : int(id: 0);
    y : int(id: 1);
}

root_type Event;

关键字

关键字 描述与用途
/// FlatBuffers中用 "///" 来表示注释,且此注释会带入到生成的源码文件中
namespace 模型目录,包结构
table 模型类标识 会生成对应标识的单个模型文件的类
bool short int float string 默认数据类型关键字
enum 枚举类数据定义
union 生成一个独立的枚举类
deprecated 指定deprecated,可以删除掉此字段
priority 设定优先权
root_type 其table生成的文件中,除Table中字段会生成相关函数外会另外生成GetRootAsXXX()的函数
required struct的每个字段都为required,table的每个字段都默认都是optional,但可以指定为required
id 设置生成指定顺序,要求这个table里面全部都写上才生效
include 引入另一个fbs内容

范例

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; ...}

/// 直接指定数据类型及默认值
mana:short = 150;

/// 指定deprecated,可以删除掉此字段
friendly:bool = false (deprecated, priority: 1);

/// 加id指定生成顺序
mana:short = 150 (id: 3); 

///
 include "include_test1.fbs"; 形式,将其它.fbs文件嵌套进来

如有加id,则table中所有字段都要加id才可通过

生成对应语言的模型文件

使用 flatc 生成对应语言的模型文件


  --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

自动更新模型文件脚本

#!/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

更新脚本是一个范例,建议自己修改~

golang 项目中使用

安装golang支持包

go get -u -v google/flatbuffers/go

golang官方使用Flatbuffers文档 http://google.github.io/flatbuffers/index.html

或者 根据范例来使用

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

你可能感兴趣的:(FlatBuffers 使用 Golang java 指引)