• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1Use in C++    {#flatbuffers_guide_use_cpp}
2==========
3
4## Before you get started
5
6Before diving into the FlatBuffers usage in C++, it should be noted that
7the [Tutorial](@ref flatbuffers_guide_tutorial) page has a complete guide
8to general FlatBuffers usage in all of the supported languages (including C++).
9This page is designed to cover the nuances of FlatBuffers usage, specific to
10C++.
11
12#### Prerequisites
13
14This page assumes you have written a FlatBuffers schema and compiled it
15with the Schema Compiler. If you have not, please see
16[Using the schema compiler](@ref flatbuffers_guide_using_schema_compiler)
17and [Writing a schema](@ref flatbuffers_guide_writing_schema).
18
19Assuming you wrote a schema, say `mygame.fbs` (though the extension doesn't
20matter), you've generated a C++ header called `mygame_generated.h` using the
21compiler (e.g. `flatc -c mygame.fbs`), you can now start using this in
22your program by including the header. As noted, this header relies on
23`flatbuffers/flatbuffers.h`, which should be in your include path.
24
25## FlatBuffers C++ library code location
26
27The code for the FlatBuffers C++ library can be found at
28`flatbuffers/include/flatbuffers`. You can browse the library code on the
29[FlatBuffers GitHub page](https://github.com/google/flatbuffers/tree/master/include/flatbuffers).
30
31## Testing the FlatBuffers C++ library
32
33The code to test the C++ library can be found at `flatbuffers/tests`.
34The test code itself is located in
35[test.cpp](https://github.com/google/flatbuffers/blob/master/tests/test.cpp).
36
37This test file is built alongside `flatc`. To review how to build the project,
38please read the [Building](@ref flatbuffers_guide_building) documenation.
39
40To run the tests, execute `flattests` from the root `flatbuffers/` directory.
41For example, on [Linux](https://en.wikipedia.org/wiki/Linux), you would simply
42run: `./flattests`.
43
44## Using the FlatBuffers C++ library
45
46*Note: See [Tutorial](@ref flatbuffers_guide_tutorial) for a more in-depth
47example of how to use FlatBuffers in C++.*
48
49FlatBuffers supports both reading and writing FlatBuffers in C++.
50
51To use FlatBuffers in your code, first generate the C++ classes from your
52schema with the `--cpp` option to `flatc`. Then you can include both FlatBuffers
53and the generated code to read or write FlatBuffers.
54
55For example, here is how you would read a FlatBuffer binary file in C++:
56First, include the library and generated code. Then read the file into
57a `char *` array, which you pass to `GetMonster()`.
58
59~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp}
60    #include "flatbuffers/flatbuffers.h"
61    #include "monster_test_generate.h"
62    #include <cstdio> // For printing and file access.
63
64    FILE* file = fopen("monsterdata_test.mon", "rb");
65    fseek(file, 0L, SEEK_END);
66    int length = ftell(file);
67    fseek(file, 0L, SEEK_SET);
68    char *data = new char[length];
69    fread(data, sizeof(char), length, file);
70    fclose(file);
71
72    auto monster = GetMonster(data);
73~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
74
75`monster` is of type `Monster *`, and points to somewhere *inside* your
76buffer (root object pointers are not the same as `buffer_pointer` !).
77If you look in your generated header, you'll see it has
78convenient accessors for all fields, e.g. `hp()`, `mana()`, etc:
79
80~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp}
81    printf("%d\n", monster->hp());            // `80`
82    printf("%d\n", monster->mana());          // default value of `150`
83    printf("%s\n", monster->name()->c_str()); // "MyMonster"
84~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
85
86*Note: That we never stored a `mana` value, so it will return the default.*
87
88## Object based API.  {#flatbuffers_cpp_object_based_api}
89
90FlatBuffers is all about memory efficiency, which is why its base API is written
91around using as little as possible of it. This does make the API clumsier
92(requiring pre-order construction of all data, and making mutation harder).
93
94For times when efficiency is less important a more convenient object based API
95can be used (through `--gen-object-api`) that is able to unpack & pack a
96FlatBuffer into objects and standard STL containers, allowing for convenient
97construction, access and mutation.
98
99To use:
100
101~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp}
102    // Autogenerated class from table Monster.
103    MonsterT monsterobj;
104
105    // Deserialize from buffer into object.
106    UnPackTo(&monsterobj, flatbuffer);
107
108    // Update object directly like a C++ class instance.
109    cout << monsterobj->name;  // This is now a std::string!
110    monsterobj->name = "Bob";  // Change the name.
111
112    // Serialize into new flatbuffer.
113    FlatBufferBuilder fbb;
114    Pack(fbb, &monsterobj);
115~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
116
117The following attributes are specific to the object-based API code generation:
118
119-   `native_inline` (on a field): Because FlatBuffer tables and structs are
120    optionally present in a given buffer, they are best represented as pointers
121    (specifically std::unique_ptrs) in the native class since they can be null.
122    This attribute changes the member declaration to use the type directly
123    rather than wrapped in a unique_ptr.
124
125-   `native_default`: "value" (on a field): For members that are declared
126    "native_inline", the value specified with this attribute will be included
127    verbatim in the class constructor initializer list for this member.
128
129-   `native_type`' "type" (on a struct): In some cases, a more optimal C++ data
130    type exists for a given struct.  For example, the following schema:
131
132      struct Vec2 {
133        x: float;
134        y: float;
135      }
136
137    generates the following Object-Based API class:
138
139      struct Vec2T : flatbuffers::NativeTable {
140        float x;
141        float y;
142      };
143
144    However, it can be useful to instead use a user-defined C++ type since it
145    can provide more functionality, eg.
146
147      struct vector2 {
148        float x = 0, y = 0;
149        vector2 operator+(vector2 rhs) const { ... }
150        vector2 operator-(vector2 rhs) const { ... }
151        float length() const { ... }
152        // etc.
153      };
154
155    The `native_type` attribute will replace the usage of the generated class
156    with the given type.  So, continuing with the example, the generated
157    code would use |vector2| in place of |Vec2T| for all generated code.
158
159    However, becuase the native_type is unknown to flatbuffers, the user must
160    provide the following functions to aide in the serialization process:
161
162      namespace flatbuffers {
163        FlatbufferStruct Pack(const native_type& obj);
164        native_type UnPack(const FlatbufferStruct& obj);
165      }
166
167Finally, the following top-level attribute
168
169-   native_include: "path" (at file level): Because the `native_type` attribute
170    can be used to introduce types that are unknown to flatbuffers, it may be
171    necessary to include "external" header files in the generated code.  This
172    attribute can be used to directly add an #include directive to the top of
173    the generated code that includes the specified path directly.
174
175# External references.
176
177An additional feature of the object API is the ability to allow you to load
178multiple independent FlatBuffers, and have them refer to eachothers objects
179using hashes which are then represented as typed pointers in the object API.
180
181To make this work have a field in the objects you want to referred to which is
182using the string hashing feature (see `hash` attribute in the
183[schema](@ref flatbuffers_guide_writing_schema) documentation). Then you have
184a similar hash in the field referring to it, along with a `cpp_type`
185attribute specifying the C++ type this will refer to (this can be any C++
186type, and will get a `*` added).
187
188Then, in JSON or however you create these buffers, make sure they use the
189same string (or hash).
190
191When you call `UnPack` (or `Create`), you'll need a function that maps from
192hash to the object (see `resolver_function_t` for details).
193
194# Using different pointer types.
195
196By default the object tree is built out of `std::unique_ptr`, but you can
197influence this either globally (using the `--cpp-ptr-type` argument to
198`flatc`) or per field (using the `cpp_ptr_type` attribute) to by any smart
199pointer type (`my_ptr<T>`), or by specifying `naked` as the type to get `T *`
200pointers. Unlike the smart pointers, naked pointers do not manage memory for
201you, so you'll have to manage their lifecycles manually.
202
203## Reflection (& Resizing)
204
205There is experimental support for reflection in FlatBuffers, allowing you to
206read and write data even if you don't know the exact format of a buffer, and
207even allows you to change sizes of strings and vectors in-place.
208
209The way this works is very elegant; there is actually a FlatBuffer schema that
210describes schemas (!) which you can find in `reflection/reflection.fbs`.
211The compiler, `flatc`, can write out any schemas it has just parsed as a binary
212FlatBuffer, corresponding to this meta-schema.
213
214Loading in one of these binary schemas at runtime allows you traverse any
215FlatBuffer data that corresponds to it without knowing the exact format. You
216can query what fields are present, and then read/write them after.
217
218For convenient field manipulation, you can include the header
219`flatbuffers/reflection.h` which includes both the generated code from the meta
220schema, as well as a lot of helper functions.
221
222And example of usage, for the time being, can be found in
223`test.cpp/ReflectionTest()`.
224
225## Storing maps / dictionaries in a FlatBuffer
226
227FlatBuffers doesn't support maps natively, but there is support to
228emulate their behavior with vectors and binary search, which means you
229can have fast lookups directly from a FlatBuffer without having to unpack
230your data into a `std::map` or similar.
231
232To use it:
233-   Designate one of the fields in a table as they "key" field. You do this
234    by setting the `key` attribute on this field, e.g.
235    `name:string (key)`.
236    You may only have one key field, and it must be of string or scalar type.
237-   Write out tables of this type as usual, collect their offsets in an
238    array or vector.
239-   Instead of `CreateVector`, call `CreateVectorOfSortedTables`,
240    which will first sort all offsets such that the tables they refer to
241    are sorted by the key field, then serialize it.
242-   Now when you're accessing the FlatBuffer, you can use `Vector::LookupByKey`
243    instead of just `Vector::Get` to access elements of the vector, e.g.:
244    `myvector->LookupByKey("Fred")`, which returns a pointer to the
245    corresponding table type, or `nullptr` if not found.
246    `LookupByKey` performs a binary search, so should have a similar speed to
247    `std::map`, though may be faster because of better caching. `LookupByKey`
248    only works if the vector has been sorted, it will likely not find elements
249    if it hasn't been sorted.
250
251## Direct memory access
252
253As you can see from the above examples, all elements in a buffer are
254accessed through generated accessors. This is because everything is
255stored in little endian format on all platforms (the accessor
256performs a swap operation on big endian machines), and also because
257the layout of things is generally not known to the user.
258
259For structs, layout is deterministic and guaranteed to be the same
260accross platforms (scalars are aligned to their
261own size, and structs themselves to their largest member), and you
262are allowed to access this memory directly by using `sizeof()` and
263`memcpy` on the pointer to a struct, or even an array of structs.
264
265To compute offsets to sub-elements of a struct, make sure they
266are a structs themselves, as then you can use the pointers to
267figure out the offset without having to hardcode it. This is
268handy for use of arrays of structs with calls like `glVertexAttribPointer`
269in OpenGL or similar APIs.
270
271It is important to note is that structs are still little endian on all
272machines, so only use tricks like this if you can guarantee you're not
273shipping on a big endian machine (an `assert(FLATBUFFERS_LITTLEENDIAN)`
274would be wise).
275
276## Access of untrusted buffers
277
278The generated accessor functions access fields over offsets, which is
279very quick. These offsets are not verified at run-time, so a malformed
280buffer could cause a program to crash by accessing random memory.
281
282When you're processing large amounts of data from a source you know (e.g.
283your own generated data on disk), this is acceptable, but when reading
284data from the network that can potentially have been modified by an
285attacker, this is undesirable.
286
287For this reason, you can optionally use a buffer verifier before you
288access the data. This verifier will check all offsets, all sizes of
289fields, and null termination of strings to ensure that when a buffer
290is accessed, all reads will end up inside the buffer.
291
292Each root type will have a verification function generated for it,
293e.g. for `Monster`, you can call:
294
295~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp}
296	bool ok = VerifyMonsterBuffer(Verifier(buf, len));
297~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
298
299if `ok` is true, the buffer is safe to read.
300
301Besides untrusted data, this function may be useful to call in debug
302mode, as extra insurance against data being corrupted somewhere along
303the way.
304
305While verifying a buffer isn't "free", it is typically faster than
306a full traversal (since any scalar data is not actually touched),
307and since it may cause the buffer to be brought into cache before
308reading, the actual overhead may be even lower than expected.
309
310In specialized cases where a denial of service attack is possible,
311the verifier has two additional constructor arguments that allow
312you to limit the nesting depth and total amount of tables the
313verifier may encounter before declaring the buffer malformed. The default is
314`Verifier(buf, len, 64 /* max depth */, 1000000, /* max tables */)` which
315should be sufficient for most uses.
316
317## Text & schema parsing
318
319Using binary buffers with the generated header provides a super low
320overhead use of FlatBuffer data. There are, however, times when you want
321to use text formats, for example because it interacts better with source
322control, or you want to give your users easy access to data.
323
324Another reason might be that you already have a lot of data in JSON
325format, or a tool that generates JSON, and if you can write a schema for
326it, this will provide you an easy way to use that data directly.
327
328(see the schema documentation for some specifics on the JSON format
329accepted).
330
331There are two ways to use text formats:
332
333#### Using the compiler as a conversion tool
334
335This is the preferred path, as it doesn't require you to add any new
336code to your program, and is maximally efficient since you can ship with
337binary data. The disadvantage is that it is an extra step for your
338users/developers to perform, though you might be able to automate it.
339
340    flatc -b myschema.fbs mydata.json
341
342This will generate the binary file `mydata_wire.bin` which can be loaded
343as before.
344
345#### Making your program capable of loading text directly
346
347This gives you maximum flexibility. You could even opt to support both,
348i.e. check for both files, and regenerate the binary from text when
349required, otherwise just load the binary.
350
351This option is currently only available for C++, or Java through JNI.
352
353As mentioned in the section "Building" above, this technique requires
354you to link a few more files into your program, and you'll want to include
355`flatbuffers/idl.h`.
356
357Load text (either a schema or json) into an in-memory buffer (there is a
358convenient `LoadFile()` utility function in `flatbuffers/util.h` if you
359wish). Construct a parser:
360
361~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp}
362    flatbuffers::Parser parser;
363~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
364
365Now you can parse any number of text files in sequence:
366
367~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp}
368    parser.Parse(text_file.c_str());
369~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
370
371This works similarly to how the command-line compiler works: a sequence
372of files parsed by the same `Parser` object allow later files to
373reference definitions in earlier files. Typically this means you first
374load a schema file (which populates `Parser` with definitions), followed
375by one or more JSON files.
376
377As optional argument to `Parse`, you may specify a null-terminated list of
378include paths. If not specified, any include statements try to resolve from
379the current directory.
380
381If there were any parsing errors, `Parse` will return `false`, and
382`Parser::err` contains a human readable error string with a line number
383etc, which you should present to the creator of that file.
384
385After each JSON file, the `Parser::fbb` member variable is the
386`FlatBufferBuilder` that contains the binary buffer version of that
387file, that you can access as described above.
388
389`samples/sample_text.cpp` is a code sample showing the above operations.
390
391## Threading
392
393Reading a FlatBuffer does not touch any memory outside the original buffer,
394and is entirely read-only (all const), so is safe to access from multiple
395threads even without synchronisation primitives.
396
397Creating a FlatBuffer is not thread safe. All state related to building
398a FlatBuffer is contained in a FlatBufferBuilder instance, and no memory
399outside of it is touched. To make this thread safe, either do not
400share instances of FlatBufferBuilder between threads (recommended), or
401manually wrap it in synchronisation primites. There's no automatic way to
402accomplish this, by design, as we feel multithreaded construction
403of a single buffer will be rare, and synchronisation overhead would be costly.
404
405<br>
406