FlatBuffer入门笔记

1 flatbuffer资料

flatbuffer下载地址:https://github.com/google/flatbuffers

flatbuffer官方使用文档:https://google.github.io/flatbuffers/index.html#flatbuffers_overview

flatbuffer官方测试用例:https://google.github.io/flatbuffers/flatbuffers_guide_use_cpp.html

2 编写IDL|Schema

2.1 IDL测试文件

  引用官方测试使用的IDL

 // Example IDL file for our monster's schema.
namespace MyGame.Sample;
enum Color:byte { Red = , Green, Blue = }
union Equipment { Weapon } // Optionally add more tables.
struct Vec3 {
x:float;
y:float;
z:float;
}
table Monster {
pos:Vec3; // Struct.
mana:short = ;
hp:short = ;
name:string;
friendly:bool = false (deprecated);
inventory:[ubyte]; // Vector of scalars.
color:Color = Blue; // Enum.
weapons:[Weapon]; // Vector of tables.
equipped:Equipment; // Union.
path:[Vec3]; // Vector of structs.
}
table Weapon {
name:string;
damage:short;
}
root_type Monster;

2.2  生成桩文件

  利用flatc.exe生成IDL对应的桩代码,命令格式为

 flatc [ GENERATOR OPTIONS ] [ -o PATH ] [ -I PATH ] [ -S ] FILES...  [ -- FILES...]
 flatc --cpp monster.fbs

  flatbuffer使用模板编程,仅生成h文件。对应的文件名为filename_generated.h。这里生成monster_generated.h文件。

2.3 IDL数据类型

2.3.1 Table

  Table是FlatBuffer定义的主要数据类型,一个Table包含一个名称(如2.1的Monster),以及一组字段(如2.1的Monster)。每个字段由名称、类型及默认值组成。

  FlatBuffer每个字段都是可选的,这由FlatBUffer的线性实现机制决定:空闲字段仅填充默认占位值,而不占用分配size。

2.3.2 Struct

  Struct只包含数值类型与其他struct,与Table相比,Struct使用更少的存储空间以及更快的访问速度。

2.3.3 Type

  内建的数值类型有:

  • 8 bit: byte (int8), ubyte (uint8), bool
  • 16 bit: short (int16), ushort (uint16)
  • 32 bit: int (int32), uint (uint32), float (float32)
  • 64 bit: long (int64), ulong (uint64), double (float64)

  内建的非数值类型有:

  • vector,用[]表示
  • string
  • 指向其他Table、struct、enum、unions的引用

2.3.4 Enums

  定义了一系列的命名常量,可以给定默认值。第一个变量的默认值为0。

2.3.5 Namespaces

  可以定义嵌套的namespace,用.分割。

2.3.6 Root type

  定义序列化的root table或者struct。

3 序列化与反序列化

  对2.1例子的序列化和反序列化过程实现在sample_binary.cpp。

3.1 序列化

  // Build up a serialized buffer algorithmically:
flatbuffers::FlatBufferBuilder builder; //申请一个flatbuffer // First, lets serialize some weapons for the Monster: A 'sword' and an 'axe'.
auto weapon_one_name = builder.CreateString("Sword"); //在buffer中申请string
short weapon_one_damage = ; auto weapon_two_name = builder.CreateString("Axe"); //在buffer中申请string
short weapon_two_damage = ; // Use the `CreateWeapon` shortcut to create Weapons with all fields set.
auto sword = CreateWeapon(builder, weapon_one_name, weapon_one_damage); //桩代码中实现
auto axe = CreateWeapon(builder, weapon_two_name, weapon_two_damage); // // Create a FlatBuffer's `vector` from the `std::vector`.
std::vector<flatbuffers::Offset<Weapon>> weapons_vector;
weapons_vector.push_back(sword);
weapons_vector.push_back(axe);
auto weapons = builder.CreateVector(weapons_vector); //在buffer中序列化vector // Second, serialize the rest of the objects needed by the Monster.
auto position = Vec3(1.0f, 2.0f, 3.0f); auto name = builder.CreateString("MyMonster"); unsigned char inv_data[] = { , , , , , , , , , };
auto inventory = builder.CreateVector(inv_data, ); // Shortcut for creating monster with all fields set:
auto orc = CreateMonster(builder, &position, , , name, inventory,
Color_Red, weapons, Equipment_Weapon, axe.Union()); builder.Finish(orc); // Serialize the root of the object. //序列化对象root // We now have a FlatBuffer we can store on disk or send over a network. // ** file/network code goes here :) **

3.2 反序列化

 // access builder.GetBufferPointer() for builder.GetSize() bytes

   // Instead, we're going to access it right away (as if we just received it).

   // Get access to the root:
auto monster = GetMonster(builder.GetBufferPointer()); //获取根对象指针 // Get and test some scalar types from the FlatBuffer.
assert(monster->hp() == );
assert(monster->mana() == ); // default
assert(monster->name()->str() == "MyMonster"); // Get and test a field of the FlatBuffer's `struct`.
auto pos = monster->pos();
assert(pos);
assert(pos->z() == 3.0f);
(void)pos; // Get a test an element from the `inventory` FlatBuffer's `vector`.
auto inv = monster->inventory();
assert(inv);
assert(inv->Get() == );
(void)inv; // Get and test the `weapons` FlatBuffers's `vector`.
std::string expected_weapon_names[] = { "Sword", "Axe" };
short expected_weapon_damages[] = { , };
auto weps = monster->weapons();
for (unsigned int i = ; i < weps->size(); i++) {
assert(weps->Get(i)->name()->str() == expected_weapon_names[i]);
assert(weps->Get(i)->damage() == expected_weapon_damages[i]);
}
(void)expected_weapon_names;
(void)expected_weapon_damages; // Get and test the `Equipment` union (`equipped` field).
assert(monster->equipped_type() == Equipment_Weapon);
auto equipped = static_cast<const Weapon *>(monster->equipped());
assert(equipped->name()->str() == "Axe");
assert(equipped->damage() == );
(void)equipped;

4 FlatBuffer原理?网上找的一些文档

  https://www.jianshu.com/p/fa999434776a

FlatBuffer入门笔记-LMLPHP

05-11 11:32