跳过正文
FlatBuffers 使用教程
  1. 文章/

FlatBuffers 使用教程

FlatBuffers是一种高效的二进制序列化格式,它使用一种简单的描述语言来定义数据结构,并生成相应的C++、Java、C#、Go、Dart、JavaScript、Lua、Rust、Swift、Kotlin、Dart、Ruby、PHP、C#、Objective-C、C、C++、Rust、Java、Python、Lua、Dart、Ruby、PHP、C#、Objective代码。

FlatBuffers 环境配置
#

安装编译依赖
#

# Linux
sudo apt update && sudo apt upgrade -y
sudo apt install -y build-essential cmake git

# MacOS
brew update && brew upgrade
brew install cmake git

编译安装 FlatBuffers
#

# 以下为Linux和MacOS下载源码进行编译流程
git clone git@github.com:google/flatbuffers.git --depth=1
cd flatbuffers

# Linux
cmake -G "Unix Makefiles" -DCMAKE_BUILD_TYPE=Release
# MacOS
cmake -G "Xcode" -DCMAKE_BUILD_TYPE=Release

# Linux
make -j$(nproc)
# MacOS
xcodebuild -toolchain clang -configuration Release

# Linux
sudo make install
# MacOS
sudo cp Release/flatc /usr/local/bin/

# Windows推荐直接下载预编译版
https://github.com/google/flatbuffers/releases
下载解压到指定目录,并将目录添加到环境变量中

测试安装成功
#

flatc --version

定义 FlatBuffers Schema 文件
#

FlatBuffers Schema 文件定义了数据结构,包含数据类型、字段、字段顺序等信息。

// monster.fbs
namespace MyGame.Sample;

enum Color:byte { Red = 0, Green, Blue }

struct Vec3 {
  x:float;
  y:float;
  z:float;
}

table Monster {
  pos:Vec3;          // 结构体字段
  mana:short = 150;  // 默认值
  hp:short = 100;
  name:string;
  color:Color = Blue;// 枚举字段
}

root_type Monster;  // 指定根类型

生成代码
#

flatc --go monster.fbs
flatc --ts monster.fbs