What's the purpose of root type in flatbuffers?

740 Views Asked by At

My understanding is that root type is some legacy thing, it is needed only for two reasons:

  1. root_type name (name, not content) is used to create some objects, for example embed binary schema.
  2. some syntax sugar API is generated only for root type. Since it is just sugar, you don't have to use it.

Am I right or am I missing something?

So for example if I do:

table Foo { ... }
table Bar {...}
...

// empty root at the end to make flatbuffers happy
table Fbs {}
root_type Fbs

I named it Fbs so that generated schema looks nice: FbsBinarySchema. Another option would be to use file name, since it contains binary schema of full file, and thus MyFileBinarySchema makes sense.

1

There are 1 best solutions below

10
Moop On

The root_type is very important for flatbuffers and is not a legacy thing.

It is used to know the type of the table referenced by the buffer, so it knows how to decode its contents.

If this is a FlatBuffer binary:

[32-bit offset to root type][... misc ...][root type][... misc ...]
             ^                            ^
             |                            |
This value has the numeric offset to  ----/

Currently in your schema, no Foo or Bar tables are accessible. You need to add them to your Fbs table:

table Fbs {
  my_field:Foo;
  my_other_field:Bar;
  collection_of_foos:[Foo];
}

So you should have a generated accessor:

const Fbs* GetFbs(uint8_t * buffer);

That allows you to get the root type/table. From there, all other things in the buffer are referenceable from the root type.

uint8_t* buffer = ... // from somewhere

const Fbs* my_fbs = GetFbs(buffer);

const Foo* my_foo = my_fbs.my_field();