Quick Start
This will quickly go over the parts of using FlatBuffers to serialize some data. See the Tutorial for a more in depth guide.
-
Build the compiler for FlatBuffers (
flatc
)cmake -G "Unix Makefiles" make -j
-
Define your FlatBuffer schema (
.fbs
)monster.fbs 1 2 3 4 5 6
table Monster { name:string; health:int; } root_type Monster;
See monster.fbs for an complete example.
-
Generate code for your language(s)
Use the
flatc
compiler to take your schema and generate language-specific code:./flatc --cpp --rust mosnter.fbs
Which generates
monster_generated.h
andmonster_generated.rs
files. -
Serialize data
Use the generated code files, as well as the
FlatBufferBuilder
to construct your serialized buffer.my_monster_factory.cc 1 2 3 4 5 6 7 8 9 10 11 12 13 14
#include "flatbuffers.h" #include "monster_generated.h" int main() { // Used to build the flatbuffer FlatBufferBuilder builder; // Auto-generated function emitted from `flatc` and the input // `monster.fbs` schema. auto monster = CreateMonsterDirect(builder, "Abominable Snowman", 100); // Finalize the buffer. builder.Finish(monster); }
See complete C++ Example.
-
Transmit/Store the serialized FlatBuffer
Use your serialized buffer however you want. Send it to someone, save if for later, etc...
my_monster_factory.cc 13 14
// Get a pointer to the flatbuffer. const uint8_t* flatbuffer = builder.GetBufferPointer();
-
Read the data
Use the generated accessors to read the data from the serialized buffer.
It doesn't need to be the same language, or even schema version (see Evolving), FlatBuffers ensures the data is readable across languages and schema versions.
my_monster_factory.cc 15 16 17 18 19 20
// Get a view of the root monster from the flatbuffer. const Monster snowman = GetMonster(flatbuffer); // Access the monster's fields directly. ASSERT_EQ(snowman->name(), "Abominable Snowman"); ASSERT_EQ(snowman->health(), 100);
See
Rust
examples for reading the data written byC++
.