FlatBuffers使用总结(3)

1、IDL测试文件

// Example IDL file for our monster's schema.
namespace MyGame.Sample;
enum Color:byte { Red = 0, Green, Blue = 2 }
union Equipment { Weapon } // Optionally add more tables.
struct Vec3 {
  x:float;
  y:float;
  z:float;
}
table Monster {
  pos:Vec3; // Struct.
  mana:short = 150;
  hp:short = 100;
  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、生成桩文件

利用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文件。

3、IDL数据类型

3.1 Table

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

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

3.2 Struct

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

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的引用

3.4  Enums

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

3.5 Namespaces

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

3.6 Root type

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

4、序列化与反序列化

4.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 = 3;

  auto weapon_two_name = builder.CreateString("Axe");                   //在buffer中申请string
  short weapon_two_damage = 5;

  // 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> 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[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
  auto inventory = builder.CreateVector(inv_data, 10);

  // Shortcut for creating monster with all fields set:
  auto orc = CreateMonster(builder, &position, 150, 80, 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 :) **

4.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() == 80);
  assert(monster->mana() == 150);  // 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(9) == 9);
  (void)inv;

  // Get and test the `weapons` FlatBuffers's `vector`.
  std::string expected_weapon_names[] = { "Sword", "Axe" };
  short expected_weapon_damages[] = { 3, 5 };
  auto weps = monster->weapons();
  for (unsigned int i = 0; 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(monster->equipped());
  assert(equipped->name()->str() == "Axe");
  assert(equipped->damage() == 5);
  (void)equipped;

其它经典博客参考:

https://www.cnblogs.com/relvin/p/5540063.html

https://www.jianshu.com/p/9e389428aaf3

 

 

你可能感兴趣的:(C++,数据结构)