Write a demo schema: monster.fbs with the reference of the offical tutorial.
namespace MyGame.Sample;
enumColor:byte { Red = 0, Green, Blue = 2 }
union Equipment { Weapon } // Optionally add more tables
struct Vec3 { x: float; // Here default value is unspecified, given it as 0 y: float; z: float; }
table Monster { pos: Vec3; // Struct mana: short = 150; hp: short = 100; name: string; friendly: bool = false (deprecated); // Will not genenate access function for deprecated field inventory: [ubyte]; // Vector of scalars color: Color = Blue; // Enum weapons: [Weapon]; // Vector of tables equipped:Equipment; // Union path: [Vec3]; // Vector of struct }
table Weapon { name: string; damage: short; }
// What will be the root table for the serialized data root_type Monster;
Q: Difference between struct and table?
A: struct is better for data structure that will no change, since they use less memory and have faster lookup.
/* Create Monster */ // Usage 1:set all fileds at once // auto orc = CreateMonster(builder, &position, mana, hp, name, // inventory, Color_Red, weapons, // Equipment_Weapon, axe.Union(), path);
// Usage 2: set specified filed as needed MonsterBuilder monster_builder(builder); monster_builder.add_pos(&position); monster_builder.add_hp(hp); monster_builder.add_name(name); monster_builder.add_mana(mana); monster_builder.add_inventory(inventory); monster_builder.add_color(Color_Red); monster_builder.add_weapons(weapons); monster_builder.add_equipped_type(Equipment_Weapon); monster_builder.add_equipped(axe.Union()); monster_builder.add_path(path); auto orc = monster_builder.Finish();
/* Invoke Finish() to end the serializing procedure. */ builder.Finish(orc);
/* Get the serializing result: a byte buffer. */ buf = builder.GetBufferPointer(); size = builder.GetSize(); }
(b). Monster Deserialization
voidDeserializeMonster(constuint8_t *buf){ /* Get deserialized root object: monster *// auto monster = GetMonster(buf);
/* Get each field of monster */ auto pos = monster->pos(); auto hp = monster->hp(); auto name = monster->name(); auto mana = monster->mana(); auto inventory = monster->inventory(); auto color = monster->color(); auto weapons = monster->weapons(); auto equipment_type = monster->equipped_type(); auto path = monster->path();
/* Access each field and print them */ cout << "pos: { x: " << pos->x() << ", y: " << pos->y() << ", z: " << pos->z() << " }" << endl; cout << "hp: " << hp << endl; cout << "name: " << name->str() << endl; cout << "mana: " << mana << endl;
cout << "inventory: { "; for (decltype(inventory->size()) i = 0; i < inventory->size(); i++) { cout << static_cast<uint32_t>((*inventory)[i]); cout << (i < inventory->size() - 1 ? ", " : " "); } cout << "}" << endl;