1. Flatbuffer 概要:

2. Flatbuffer 安装:
$ choice "folder for installation"
$ cd "folder for installation"
$ git clone https://github.com/google/flatbuffers.git
$ cd flatbuffers
$ cmake -G "Unix Makefiles" (install cmake if need)
$ make && sudo make install
3. Flatbuffer write schema/jsonfile
3.1 schema(左) vs json(右)

3.2 手写schema 以及 jsonfile
namespace MyGame;
attribute "priority";
enum Color : byte { Red = 1, Green, Blue }
union Any { Monster }
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;
}
root_type Monster;
{
"pos": {
"x": "1.0",
"y": "2.0",
"z": "3.0"
},
"mana": "200",
"name": "jianlei",
"inventory" :
[
"1",
"2",
"3"
],
"color": "Green"
}
4. Flatbuffer fbs/json compile
4.1 fbs comile
flatc -c mygame.fbs
4.2 json compile
flatc -b mygame.fbs mygame.json
4.3 app.cpp usage
#include "flatbuffers/flatbuffers.h"
#include "mygame_generated.h"
#include <iostream>
#include <fstream>
std::ifstream infile;
infile.open("mygame.bin", std::ios::binary | std::ios::in);
infile.seekg(0,std::ios::end);
int length = infile.tellg();
infile.seekg(0,std::ios::beg);
char *data = new char[length];
infile.read(data, length);
infile.close();
auto monster = GetMonster(data);
std::cout << "hp : " << monster->hp() << std::endl;
std::cout << "mana : " << monster->mana() << std::endl;
std::cout << "name : " << monster->name()->c_str() << std::endl;
return 0;
}
5. Flatbuffer 资料: