• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1Tutorial   {#flatbuffers_guide_tutorial}
2========
3
4## Overview
5
6This tutorial provides a basic example of how to work with
7[FlatBuffers](@ref flatbuffers_overview). We will step through a simple example
8application, which shows you how to:
9
10   - Write a FlatBuffer `schema` file.
11   - Use the `flatc` FlatBuffer compiler.
12   - Parse [JSON](http://json.org) files that conform to a schema into
13     FlatBuffer binary files.
14   - Use the generated files in many of the supported languages (such as C++,
15     Java, and more.)
16
17During this example, imagine that you are creating a game where the main
18character, the hero of the story, needs to slay some `orc`s. We will walk
19through each step necessary to create this monster type using FlatBuffers.
20
21Please select your desired language for our quest:
22\htmlonly
23<form>
24  <input type="radio" name="language" value="cpp" checked="checked">C++</input>
25  <input type="radio" name="language" value="java">Java</input>
26  <input type="radio" name="language" value="csharp">C#</input>
27  <input type="radio" name="language" value="go">Go</input>
28  <input type="radio" name="language" value="python">Python</input>
29  <input type="radio" name="language" value="javascript">JavaScript</input>
30  <input type="radio" name="language" value="php">PHP</input>
31  <input type="radio" name="language" value="c">C</input>
32</form>
33\endhtmlonly
34
35\htmlonly
36<script>
37  /**
38   * Check if an HTML `class` attribute is in the language-specific format.
39   * @param {string} languageClass An HTML `class` attribute in the format
40   * 'language-{lang}', where {lang} is a programming language (e.g. 'cpp',
41   * 'java', 'go', etc.).
42   * @return {boolean} Returns `true` if `languageClass` was in the valid
43   * format, prefixed with 'language-'. Otherwise, it returns false.
44   */
45  function isProgrammingLanguageClassName(languageClass) {
46    if (languageClass && languageClass.substring(0, 9) == 'language-' &&
47        languageClass.length > 8) {
48      return true;
49    } else {
50      return false;
51    }
52  }
53
54  /**
55   * Given a language-specific HTML `class` attribute, extract the language.
56   * @param {string} languageClass The string name of an HTML `class` attribute,
57   * in the format `language-{lang}`, where {lang} is a programming language
58   * (e.g. 'cpp', 'java', 'go', etc.).
59   * @return {string} Returns a string containing only the {lang} portion of
60   * the class name. If the input was invalid, then it returns `null`.
61   */
62  function extractProgrammingLanguageFromLanguageClass(languageClass) {
63    if (isProgrammingLanguageClassName(languageClass)) {
64      return languageClass.substring(9);
65    } else {
66      return null;
67    }
68  }
69
70  /**
71   * Hide every code snippet, except for the language that is selected.
72   */
73  function displayChosenLanguage() {
74    var selection = $('input:checked').val();
75
76    var htmlElements = document.getElementsByTagName('*');
77    for (var i = 0; i < htmlElements.length; i++) {
78      if (isProgrammingLanguageClassName(htmlElements[i].className)) {
79        if (extractProgrammingLanguageFromLanguageClass(
80              htmlElements[i].className).toLowerCase() != selection) {
81          htmlElements[i].style.display = 'none';
82        } else {
83          htmlElements[i].style.display = 'initial';
84        }
85      }
86    }
87  }
88
89  $( document ).ready(displayChosenLanguage);
90
91  $('input[type=radio]').on("click", displayChosenLanguage);
92</script>
93\endhtmlonly
94
95## Where to Find the Example Code
96
97Samples demonstating the concepts in this example are located in the source code
98package, under the `samples` directory. You can browse the samples on GitHub
99[here](https://github.com/google/flatbuffers/tree/master/samples).
100
101<div class="language-c">
102*Note: The above does not apply to C, instead [look here](https://github.com/dvidelabs/flatcc/tree/master/samples).*
103</div>
104
105For your chosen language, please cross-reference with:
106
107<div class="language-cpp">
108[sample_binary.cpp](https://github.com/google/flatbuffers/blob/master/samples/sample_binary.cpp)
109</div>
110<div class="language-java">
111[SampleBinary.java](https://github.com/google/flatbuffers/blob/master/samples/SampleBinary.java)
112</div>
113<div class="language-csharp">
114[SampleBinary.cs](https://github.com/google/flatbuffers/blob/master/samples/SampleBinary.cs)
115</div>
116<div class="language-go">
117[sample_binary.go](https://github.com/google/flatbuffers/blob/master/samples/sample_binary.go)
118</div>
119<div class="language-python">
120[sample_binary.py](https://github.com/google/flatbuffers/blob/master/samples/sample_binary.py)
121</div>
122<div class="language-javascript">
123[samplebinary.js](https://github.com/google/flatbuffers/blob/master/samples/samplebinary.js)
124</div>
125<div class="language-php">
126[SampleBinary.php](https://github.com/google/flatbuffers/blob/master/samples/SampleBinary.php)
127</div>
128<div class="language-c">
129[monster.c](https://github.com/dvidelabs/flatcc/blob/master/samples/monster/monster.c)
130</div>
131
132## Writing the Monsters' FlatBuffer Schema
133
134To start working with FlatBuffers, you first need to create a `schema` file,
135which defines the format for each data structure you wish to serialize. Here is
136the `schema` that defines the template for our monsters:
137
138~~~
139  // Example IDL file for our monster's schema.
140
141  namespace MyGame.Sample;
142
143  enum Color:byte { Red = 0, Green, Blue = 2 }
144
145  union Equipment { Weapon } // Optionally add more tables.
146
147  struct Vec3 {
148    x:float;
149    y:float;
150    z:float;
151  }
152
153  table Monster {
154    pos:Vec3; // Struct.
155    mana:short = 150;
156    hp:short = 100;
157    name:string;
158    friendly:bool = false (deprecated);
159    inventory:[ubyte];  // Vector of scalars.
160    color:Color = Blue; // Enum.
161    weapons:[Weapon];   // Vector of tables.
162    equipped:Equipment; // Union.
163  }
164
165  table Weapon {
166    name:string;
167    damage:short;
168  }
169
170  root_type Monster;
171~~~
172
173As you can see, the syntax for the `schema`
174[Interface Definition Language (IDL)](https://en.wikipedia.org/wiki/Interface_description_language)
175is similar to those of the C family of languages, and other IDL languages. Let's
176examine each part of this `schema` to determine what it does.
177
178The `schema` starts with a `namespace` declaration. This determines the
179corresponding package/namespace for the generated code. In our example, we have
180the `Sample` namespace inside of the `MyGame` namespace.
181
182Next, we have an `enum` definition. In this example, we have an `enum` of type
183`byte`, named `Color`. We have three values in this `enum`: `Red`, `Green`, and
184`Blue`. We specify `Red = 0` and `Blue = 2`, but we do not specify an explicit
185value for `Green`. Since the behavior of an `enum` is to increment if
186unspecified, `Green` will receive the implicit value of `1`.
187
188Following the `enum` is a `union`. The `union` in this example is not very
189useful, as it only contains the one `table` (named `Weapon`). If we had created
190multiple tables that we would want the `union` to be able to reference, we
191could add more elements to the `union Equipment`.
192
193After the `union` comes a `struct Vec3`, which represents a floating point
194vector with `3` dimensions. We use a `struct` here, over a `table`, because
195`struct`s are ideal for data structures that will not change, since they use
196less memory and have faster lookup.
197
198The `Monster` table is the main object in our FlatBuffer. This will be used as
199the template to store our `orc` monster. We specify some default values for
200fields, such as `mana:short = 150`. All unspecified fields will default to `0`
201or `NULL`. Another thing to note is the line
202`friendly:bool = false (deprecated);`. Since you cannot delete fields from a
203`table` (to support backwards compatability), you can set fields as
204`deprecated`, which will prevent the generation of accessors for this field in
205the generated code. Be careful when using `deprecated`, however, as it may break
206legacy code that used this accessor.
207
208The `Weapon` table is a sub-table used within our FlatBuffer. It is
209used twice: once within the `Monster` table and once within the `Equipment`
210enum. For our `Monster`, it is used to populate a `vector of tables` via the
211`weapons` field within our `Monster`. It is also the only table referenced by
212the `Equipment` enum.
213
214The last part of the `schema` is the `root_type`. The root type declares what
215will be the root table for the serialized data. In our case, the root type is
216our `Monster` table.
217
218#### More Information About Schemas
219
220You can find a complete guide to writing `schema` files in the
221[Writing a schema](@ref flatbuffers_guide_writing_schema) section of the
222Programmer's Guide. You can also view the formal
223[Grammar of the schema language](@ref flatbuffers_grammar).
224
225## Compiling the Monsters' Schema
226
227After you have written the FlatBuffers schema, the next step is to compile it.
228
229If you have not already done so, please follow
230[these instructions](@ref flatbuffers_guide_building) to build `flatc`, the
231FlatBuffer compiler.
232
233Once `flatc` is built successfully, compile the schema for your language:
234
235<div class="language-c">
236*Note: If you're working in C, you need to use the separate project [FlatCC](https://github.com/dvidelabs/flatcc) which contains a schema compiler and runtime library in C for C.*
237<br>
238See [flatcc build instructions](https://github.com/dvidelabs/flatcc#building).
239<br>
240Please be aware of the difference between `flatc` and `flatcc` tools.
241<br>
242</div>
243
244<div class="language-cpp">
245~~~{.sh}
246  cd flatbuffers/sample
247  ./../flatc --cpp samples/monster.fbs
248~~~
249</div>
250<div class="language-java">
251~~~{.sh}
252  cd flatbuffers/sample
253  ./../flatc --java samples/monster.fbs
254~~~
255</div>
256<div class="language-csharp">
257~~~{.sh}
258  cd flatbuffers/sample
259  ./../flatc --csharp samples/monster.fbs
260~~~
261</div>
262<div class="language-go">
263~~~{.sh}
264  cd flatbuffers/sample
265  ./../flatc --go samples/monster.fbs
266~~~
267</div>
268<div class="language-python">
269~~~{.sh}
270  cd flatbuffers/sample
271  ./../flatc --python samples/monster.fbs
272~~~
273</div>
274<div class="language-javascript">
275~~~{.sh}
276  cd flatbuffers/sample
277  ./../flatc --javascript samples/monster.fbs
278~~~
279</div>
280<div class="language-php">
281~~~{.sh}
282  cd flatbuffers/sample
283  ./../flatc --php samples/monster.fbs
284~~~
285</div>
286<div class="language-c">
287~~~{.sh}
288  cd flatcc
289  mkdir -p build/tmp/samples/monster
290  bin/flatcc -a -o build/tmp/samples/monster samples/monster/monster.fbs
291  # or just
292  flatcc/samples/monster/build.sh
293~~~
294</div>
295
296For a more complete guide to using the `flatc` compiler, please read the
297[Using the schema compiler](@ref flatbuffers_guide_using_schema_compiler)
298section of the Programmer's Guide.
299
300## Reading and Writing Monster FlatBuffers
301
302Now that we have compiled the schema for our programming language, we can
303start creating some monsters and serializing/deserializing them from
304FlatBuffers.
305
306#### Creating and Writing Orc FlatBuffers
307
308The first step is to import/include the library, generated files, etc.
309
310<div class="language-cpp">
311~~~{.cpp}
312  #include "monster_generate.h" // This was generated by `flatc`.
313
314  using namespace MyGame::Sample; // Specified in the schema.
315~~~
316</div>
317<div class="language-java">
318~~~{.java}
319  import MyGame.Sample.*; //The `flatc` generated files. (Monster, Vec3, etc.)
320
321  import com.google.flatbuffers.FlatBufferBuilder;
322~~~
323</div>
324<div class="language-csharp">
325~~~{.cs}
326  using FlatBuffers;
327  using MyGame.Sample; // The `flatc` generated files. (Monster, Vec3, etc.)
328~~~
329</div>
330<div class="language-go">
331~~~{.go}
332  import (
333          flatbuffers "github.com/google/flatbuffers/go"
334          sample "MyGame/Sample"
335  )
336~~~
337</div>
338<div class="language-python">
339~~~{.py}
340  import flatbuffers
341
342  # Generated by `flatc`.
343  import MyGame.Sample.Color
344  import MyGame.Sample.Equipment
345  import MyGame.Sample.Monster
346  import MyGame.Sample.Vec3
347  import MyGame.Sample.Weapon
348~~~
349</div>
350<div class="language-javascript">
351~~~{.js}
352  // The following code is for JavaScript module loaders (e.g. Node.js). See
353  // below for a browser-based HTML/JavaScript example of including the library.
354  var flatbuffers = require('/js/flatbuffers').flatbuffers;
355  var MyGame = require('./monster_generated').MyGame; // Generated by `flatc`.
356
357  //--------------------------------------------------------------------------//
358
359  // The following code is for browser-based HTML/JavaScript. Use the above code
360  // for JavaScript module loaders (e.g. Node.js).
361  <script src="../js/flatbuffers.js"></script>
362  <script src="monster_generated.js"></script> // Generated by `flatc`.
363~~~
364</div>
365<div class="language-php">
366~~~{.php}
367  // It is recommended that your use PSR autoload when using FlatBuffers in PHP.
368  // Here is an example from `SampleBinary.php`:
369  function __autoload($class_name) {
370    // The last segment of the class name matches the file name.
371    $class = substr($class_name, strrpos($class_name, "\\") + 1);
372    $root_dir = join(DIRECTORY_SEPARATOR, array(dirname(dirname(__FILE__)))); // `flatbuffers` root.
373
374    // Contains the `*.php` files for the FlatBuffers library and the `flatc` generated files.
375    $paths = array(join(DIRECTORY_SEPARATOR, array($root_dir, "php")),
376                   join(DIRECTORY_SEPARATOR, array($root_dir, "samples", "MyGame", "Sample")));
377    foreach ($paths as $path) {
378      $file = join(DIRECTORY_SEPARATOR, array($path, $class . ".php"));
379      if (file_exists($file)) {
380        require($file);
381        break;
382      }
383    }
384  }
385~~~
386</div>
387<div class="language-c">
388~~~{.c}
389  #include "monster_builder.h" // Generated by `flatcc`.
390
391  // Convenient namespace macro to manage long namespace prefix.
392  #undef ns
393  #define ns(x) FLATBUFFERS_WRAP_NAMESPACE(MyGame_Sample, x) // Specified in the schema.
394
395  // A helper to simplify creating vectors from C-arrays.
396  #define c_vec_len(V) (sizeof(V)/sizeof((V)[0]))
397~~~
398</div>
399
400Now we are ready to start building some buffers. In order to start, we need
401to create an instance of the `FlatBufferBuilder`, which will contain the buffer
402as it grows. You can pass an initial size of the buffer (here 1024 bytes),
403which will grow automatically if needed:
404
405<div class="language-cpp">
406~~~{.cpp}
407  // Create a `FlatBufferBuilder`, which will be used to create our
408  // monsters' FlatBuffers.
409  flatbuffers::FlatBufferBuilder builder(1024);
410~~~
411</div>
412<div class="language-java">
413~~~{.java}
414  // Create a `FlatBufferBuilder`, which will be used to create our
415  // monsters' FlatBuffers.
416  FlatBufferBuilder builder = new FlatBufferBuilder(1024);
417~~~
418</div>
419<div class="language-csharp">
420~~~{.cs}
421  // Create a `FlatBufferBuilder`, which will be used to create our
422  // monsters' FlatBuffers.
423  var builder = new FlatBufferBuilder(1024);
424~~~
425</div>
426<div class="language-go">
427~~~{.go}
428  // Create a `FlatBufferBuilder`, which will be used to create our
429  // monsters' FlatBuffers.
430  builder := flatbuffers.NewBuilder(1024)
431~~~
432</div>
433<div class="language-python">
434~~~{.py}
435  # Create a `FlatBufferBuilder`, which will be used to create our
436  # monsters' FlatBuffers.
437  builder = flatbuffers.Builder(1024)
438~~~
439</div>
440<div class="language-javascript">
441~~~{.js}
442  // Create a `flatbuffer.Builder`, which will be used to create our
443  // monsters' FlatBuffers.
444  var builder = new flatbuffers.Builder(1024);
445~~~
446</div>
447<div class="language-php">
448~~~{.php}
449  // Create a `FlatBufferBuilder`, which will be used to create our
450  // monsters' FlatBuffers.
451  $builder = new Google\FlatBuffers\FlatbufferBuilder(1024);
452~~~
453</div>
454<div class="language-c">
455~~~{.c}
456    flatcc_builder_t builder, *B;
457    B = &builder;
458    // Initialize the builder object.
459    flatcc_builder_init(B);
460~~~
461</div>
462
463After creating the `builder`, we can start serializing our data. Before we make
464our `orc` Monster, lets create some `Weapon`s: a `Sword` and an `Axe`.
465
466<div class="language-cpp">
467~~~{.cpp}
468  auto weapon_one_name = builder.CreateString("Sword");
469  short weapon_one_damage = 3;
470
471  auto weapon_two_name = builder.CreateString("Axe");
472  short weapon_two_damage = 5;
473
474  // Use the `CreateWeapon` shortcut to create Weapons with all the fields set.
475  auto sword = CreateWeapon(builder, weapon_one_name, weapon_one_damage);
476  auto axe = CreateWeapon(builder, weapon_two_name, weapon_two_damage);
477~~~
478</div>
479<div class="language-java">
480~~~{.java}
481  int weaponOneName = builder.createString("Sword")
482  short weaponOneDamage = 3;
483
484  int weaponTwoName = builder.createString("Axe");
485  short weaponTwoDamage = 5;
486
487  // Use the `createWeapon()` helper function to create the weapons, since we set every field.
488  int sword = Weapon.createWeapon(builder, weaponOneName, weaponOneDamage);
489  int axe = Weapon.createWeapon(builder, weaponTwoName, weaponTwoDamage);
490~~~
491</div>
492<div class="language-csharp">
493~~~{.cs}
494  var weaponOneName = builder.CreateString("Sword");
495  var weaponOneDamage = 3;
496
497  var weaponTwoName = builder.CreateString("Axe");
498  var weaponTwoDamage = 5;
499
500  // Use the `CreateWeapon()` helper function to create the weapons, since we set every field.
501  var sword = Weapon.CreateWeapon(builder, weaponOneName, (short)weaponOneDamage);
502  var axe = Weapon.CreateWeapon(builder, weaponTwoName, (short)weaponTwoDamage);
503~~~
504</div>
505<div class="language-go">
506~~~{.go}
507  weaponOne := builder.CreateString("Sword")
508  weaponTwo := builder.CreateString("Axe")
509
510  // Create the first `Weapon` ("Sword").
511  sample.WeaponStart(builder)
512  sample.Weapon.AddName(builder, weaponOne)
513  sample.Weapon.AddDamage(builder, 3)
514  sword := sample.WeaponEnd(builder)
515
516  // Create the second `Weapon` ("Axe").
517  sample.WeaponStart(builder)
518  sample.Weapon.AddName(builder, weaponTwo)
519  sample.Weapon.AddDamage(builder, 5)
520  axe := sample.WeaponEnd(builder)
521~~~
522</div>
523<div class="language-python">
524~~~{.py}
525  weapon_one = builder.CreateString('Sword')
526  weapon_two = builder.CreateString('Axe')
527
528  # Create the first `Weapon` ('Sword').
529  MyGame.Sample.Weapon.WeaponStart(builder)
530  MyGame.Sample.Weapon.WeaponAddName(builder, weapon_one)
531  MyGame.Sample.Weapon.WeaponAddDamage(builder, 3)
532  sword = MyGame.Sample.Weapon.WeaponEnd(builder)
533
534  # Create the second `Weapon` ('Axe').
535  MyGame.Sample.Weapon.WeaponStart(builder)
536  MyGame.Sample.Weapon.WeaponAddName(builder, weapon_two)
537  MyGame.Sample.Weapon.WeaponAddDamage(builder, 5)
538  axe = MyGame.Sample.Weapon.WeaponEnd(builder)
539~~~
540</div>
541<div class="language-javascript">
542~~~{.js}
543  var weaponOne = builder.createString('Sword');
544  var weaponTwo = builder.createString('Axe');
545
546  // Create the first `Weapon` ('Sword').
547  MyGame.Sample.Weapon.startWeapon(builder);
548  MyGame.Sample.Weapon.addName(builder, weaponOne);
549  MyGame.Sample.Weapon.addDamage(builder, 3);
550  var sword = MyGame.Sample.Weapon.endWeapon(builder);
551
552  // Create the second `Weapon` ('Axe').
553  MyGame.Sample.Weapon.startWeapon(builder);
554  MyGame.Sample.Weapon.addName(builder, weaponTwo);
555  MyGame.Sample.Weapon.addDamage(builder, 5);
556  var axe = MyGame.Sample.Weapon.endWeapon(builder);
557~~~
558</div>
559<div class="language-php">
560~~~{.php}
561  // Create the `Weapon`s using the `createWeapon()` helper function.
562  $weapon_one_name = $builder->createString("Sword");
563  $sword = \MyGame\Sample\Weapon::CreateWeapon($builder, $weapon_one_name, 3);
564
565  $weapon_two_name = $builder->createString("Axe");
566  $axe = \MyGame\Sample\Weapon::CreateWeapon($builder, $weapon_two_name, 5);
567
568  // Create an array from the two `Weapon`s and pass it to the
569  // `CreateWeaponsVector()` method to create a FlatBuffer vector.
570  $weaps = array($sword, $axe);
571  $weapons = \MyGame\Sample\Monster::CreateWeaponsVector($builder, $weaps);
572~~~
573</div>
574<div class="language-c">
575~~~{.c}
576  ns(Weapon_ref_t) weapon_one_name = flatbuffers_string_create_str(B, "Sword");
577  uint16_t weapon_one_damage = 3;
578
579  ns(Weapon_ref_t) weapon_two_name = flatbuffers_string_create_str(B, "Axe");
580  uint16_t weapon_two_damage = 5;
581
582  ns(Weapon_ref_t) sword = ns(Weapon_create(B, weapon_one_name, weapon_one_damage));
583  ns(Weapon_ref_t) axe = ns(Weapon_create(B, weapon_two_name, weapon_two_damage));
584~~~
585</div>
586
587Now let's create our monster, the `orc`. For this `orc`, lets make him
588`red` with rage, positioned at `(1.0, 2.0, 3.0)`, and give him
589a large pool of hit points with `300`. We can give him a vector of weapons
590to choose from (our `Sword` and `Axe` from earlier). In this case, we will
591equip him with the `Axe`, since it is the most powerful of the two. Lastly,
592let's fill his inventory with some potential treasures that can be taken once he
593is defeated.
594
595Before we serialize a monster, we need to first serialize any objects that are
596contained there-in, i.e. we serialize the data tree using depth-first, pre-order
597traversal. This is generally easy to do on any tree structures.
598
599<div class="language-cpp">
600~~~{.cpp}
601  // Serialize a name for our monster, called "Orc".
602  auto name = builder.CreateString("Orc");
603
604  // Create a `vector` representing the inventory of the Orc. Each number
605  // could correspond to an item that can be claimed after he is slain.
606  unsigned char treasure = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
607  auto inventory = builder.CreateVector(treasure, 10);
608~~~
609</div>
610<div class="language-java">
611~~~{.java}
612  // Serialize a name for our monster, called "Orc".
613  int name = builder.createString("Orc");
614
615  // Create a `vector` representing the inventory of the Orc. Each number
616  // could correspond to an item that can be claimed after he is slain.
617  byte[] treasure = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
618  int inv = Monster.createInventoryVector(builder, treasure);
619~~~
620</div>
621<div class="language-csharp">
622~~~{.cs}
623  // Serialize a name for our monster, called "Orc".
624  var name = builder.CreateString("Orc");
625
626  // Create a `vector` representing the inventory of the Orc. Each number
627  // could correspond to an item that can be claimed after he is slain.
628  // Note: Since we prepend the bytes, this loop iterates in reverse order.
629  Monster.StartInventoryVector(builder, 10);
630  for (int i = 9; i >= 0; i--)
631  {
632    builder.AddByte((byte)i);
633  }
634  var inv = builder.EndVector();
635~~~
636</div>
637<div class="language-go">
638~~~{.go}
639  // Serialize a name for our monster, called "Orc".
640  name := builder.CreateString("Orc")
641
642  // Create a `vector` representing the inventory of the Orc. Each number
643  // could correspond to an item that can be claimed after he is slain.
644  // Note: Since we prepend the bytes, this loop iterates in reverse.
645  sample.MonsterStartInventoryVector(builder, 10)
646  for i := 9; i >= 0; i-- {
647          builder.PrependByte(byte(i))
648  }
649  int := builder.EndVector(10)
650~~~
651</div>
652<div class="language-python">
653~~~{.py}
654  # Serialize a name for our monster, called "Orc".
655  name = builder.CreateString("Orc")
656
657  # Create a `vector` representing the inventory of the Orc. Each number
658  # could correspond to an item that can be claimed after he is slain.
659  # Note: Since we prepend the bytes, this loop iterates in reverse.
660  MyGame.Sample.Monster.MonsterStartInventoryVector(builder, 10)
661  for i in reversed(range(0, 10)):
662    builder.PrependByte(i)
663  inv = builder.EndVector(10)
664~~~
665</div>
666<div class="language-javascript">
667~~~{.js}
668  // Serialize a name for our monster, called 'Orc'.
669  var name = builder.createString('Orc');
670
671  // Create a `vector` representing the inventory of the Orc. Each number
672  // could correspond to an item that can be claimed after he is slain.
673  var treasure = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
674  var inv = MyGame.Sample.Monster.createInventoryVector(builder, treasure);
675~~~
676</div>
677<div class="language-php">
678~~~{.php}
679  // Serialize a name for our monster, called "Orc".
680  $name = $builder->createString("Orc");
681
682  // Create a `vector` representing the inventory of the Orc. Each number
683  // could correspond to an item that can be claimed after he is slain.
684  $treasure = array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
685  $inv = \MyGame\Sample\Monster::CreateInventoryVector($builder, $treasure);
686~~~
687</div>
688<div class="language-c">
689~~~{.c}
690  // Serialize a name for our monster, called "Orc".
691  // The _str suffix indicates the source is an ascii-z string.
692  flatbuffers_string_ref_t name = flatbuffers_string_create_str(B, "Orc");
693
694  // Create a `vector` representing the inventory of the Orc. Each number
695  // could correspond to an item that can be claimed after he is slain.
696  uint8_t treasure[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
697  flatbuffers_uint8_vec_ref_t inventory;
698  // `c_vec_len` is the convenience macro we defined earlier.
699  inventory = flatbuffers_uint8_vec_create(B, treasure, c_vec_len(treasure));
700~~~
701</div>
702
703We serialized two built-in data types (`string` and `vector`) and captured
704their return values. These values are offsets into the serialized data,
705indicating where they are stored, such that we can refer to them below when
706adding fields to our monster.
707
708*Note: To create a `vector` of nested objects (e.g. `table`s, `string`s, or
709other `vector`s), collect their offsets into a temporary data structure, and
710then create an additional `vector` containing their offsets.*
711
712For example, take a look at the two `Weapon`s that we created earlier (`Sword`
713and `Axe`). These are both FlatBuffer `table`s, whose offsets we now store in
714memory. Therefore we can create a FlatBuffer `vector` to contain these
715offsets.
716
717<div class="language-cpp">
718~~~{.cpp}
719  // Place the weapons into a `std::vector`, then convert that into a FlatBuffer `vector`.
720  std::vector<flatbuffers::Offset<Weapon>> weapons_vector;
721  weapons_vector.push_back(sword);
722  weapons_vector.push_back(axe);
723  auto weapons = builder.CreateVector(weapons_vector);
724~~~
725</div>
726<div class="language-java">
727~~~{.java}
728  // Place the two weapons into an array, and pass it to the `createWeaponsVector()` method to
729  // create a FlatBuffer vector.
730  int[] weaps = new int[2];
731  weaps[0] = sword;
732  weaps[1] = axe;
733
734  // Pass the `weaps` array into the `createWeaponsVector()` method to create a FlatBuffer vector.
735  int weapons = Monster.createWeaponsVector(builder, weaps);
736~~~
737</div>
738<div class="language-csharp">
739~~~{.cs}
740  var weaps = new Offset<Weapon>[2];
741  weaps[0] = sword;
742  weaps[1] = axe;
743
744  // Pass the `weaps` array into the `CreateWeaponsVector()` method to create a FlatBuffer vector.
745  var weapons = Monster.CreateWeaponsVector(builder, weaps);
746~~~
747</div>
748<div class="language-go">
749~~~{.go}
750  // Create a FlatBuffer vector and prepend the weapons.
751  // Note: Since we prepend the data, prepend them in reverse order.
752  sample.MonsterStartWeaponsVector(builder, 2)
753  builder.PrependUOffsetT(axe)
754  builder.PrependUOffsetT(sword)
755  weapons := builder.EndVector(2)
756~~~
757</div>
758<div class="language-python">
759~~~{.py}
760  # Create a FlatBuffer vector and prepend the weapons.
761  # Note: Since we prepend the data, prepend them in reverse order.
762  MyGame.Sample.Monster.MonsterStartWeaponsVector(builder, 2)
763  builder.PrependUOffsetTRelative(axe)
764  builder.PrependUOffsetTRelative(sword)
765  weapons = builder.EndVector(2)
766~~~
767</div>
768<div class="language-javascript">
769~~~{.js}
770  // Create an array from the two `Weapon`s and pass it to the
771  // `createWeaponsVector()` method to create a FlatBuffer vector.
772  var weaps = [sword, axe];
773  var weapons = MyGame.Sample.Monster.createWeaponsVector(builder, weaps);
774~~~
775</div>
776<div class="language-php">
777~~~{.php}
778  // Create an array from the two `Weapon`s and pass it to the
779  // `CreateWeaponsVector()` method to create a FlatBuffer vector.
780  $weaps = array($sword, $axe);
781  $weapons = \MyGame\Sample\Monster::CreateWeaponsVector($builder, $weaps);
782~~~
783</div>
784<div class="language-c">
785~~~{.c}
786  // We use the internal builder stack to implement a dynamic vector.
787  ns(Weapon_vec_start(B));
788  ns(Weapon_vec_push(B, sword));
789  ns(Weapon_vec_push(B, axe));
790  ns(Weapon_vec_ref_t) weapons = ns(Weapon_vec_end(B));
791~~~
792</div>
793
794<div class="language-cpp">
795<br>
796Note there's additional convenience overloads of `CreateVector`, allowing you
797to work with data that's not in a `std::vector`, or allowing you to generate
798elements by calling a lambda. For the common case of `std::vector<std::string>`
799there's also `CreateVectorOfStrings`.
800</div>
801
802We have now serialized the non-scalar components of the orc, so we
803can serialize the monster itself:
804
805<div class="language-cpp">
806~~~{.cpp}
807  // Set his hit points to 300 and his mana to 150.
808  int hp = 300;
809  int mana = 150;
810
811  // Finally, create the monster using the `CreateMonster` helper function
812  // to set all fields.
813  auto orc = CreateMonster(builder, Vec3(1.0f, 2.0f, 3.0f), mana, hp, name,
814                           inventory, Color_Red, weapons, Equipment_Weapon,
815                           axe.Union());
816~~~
817</div>
818<div class="language-java">
819~~~{.java}
820  // Create our monster using `startMonster()` and `endMonster()`.
821  Monster.startMonster(builder);
822  Monster.addPos(builder, Vec3.createVec3(builder, 1.0f, 2.0f, 3.0f));
823  Monster.addName(builder, name);
824  Monster.addColor(builder, Color.Red);
825  Monster.addHp(builder, (short)300);
826  Monster.addInventory(builder, inv);
827  Monster.addWeapons(builder, weapons);
828  Monster.addEquippedType(builder, Equipment.Weapon);
829  Monster.addEquipped(builder, axe);
830  int orc = Monster.endMonster(builder);
831~~~
832</div>
833<div class="language-csharp">
834~~~{.cs}
835  // Create our monster using `StartMonster()` and `EndMonster()`.
836  Monster.StartMonster(builder);
837  Monster.AddPos(builder, Vec3.CreateVec3(builder, 1.0f, 2.0f, 3.0f));
838  Monster.AddHp(builder, (short)300);
839  Monster.AddName(builder, name);
840  Monster.AddInventory(builder, inv);
841  Monster.AddColor(builder, Color.Red);
842  Monster.AddWeapons(builder, weapons);
843  Monster.AddEquippedType(builder, Equipment.Weapon);
844  Monster.AddEquipped(builder, axe.Value); // Axe
845  var orc = Monster.EndMonster(builder);
846~~~
847</div>
848<div class="language-go">
849~~~{.go}
850  // Create our monster using `MonsterStart()` and `MonsterEnd()`.
851  sample.MonsterStart(builder)
852  sample.MonsterAddPos(builder, sample.CreateVec3(builder, 1.0, 2.0, 3.0))
853  sample.MonsterAddHp(builder, 300)
854  sample.MonsterAddName(builder, name)
855  sample.MonsterAddInventory(builder, inv)
856  sample.MonsterAddColor(builder, sample.ColorRed)
857  sample.MonsterAddWeapons(builder, weapons)
858  sample.MonsterAddEquippedType(builder, sample.EquipmentWeapon)
859  sample.MonsterAddEquipped(builder, axe)
860  orc := sample.MonsterEnd(builder)
861~~~
862</div>
863<div class="language-python">
864~~~{.py}
865  # Create our monster by using `MonsterStart()` and `MonsterEnd()`.
866  MyGame.Sample.Monster.MonsterStart(builder)
867  MyGame.Sample.Monster.MonsterAddPos(builder,
868                          MyGame.Sample.Vec3.CreateVec3(builder, 1.0, 2.0, 3.0))
869  MyGame.Sample.Monster.MonsterAddHp(builder, 300)
870  MyGame.Sample.Monster.MonsterAddName(builder, name)
871  MyGame.Sample.Monster.MonsterAddInventory(builder, inv)
872  MyGame.Sample.Monster.MonsterAddColor(builder,
873                                        MyGame.Sample.Color.Color().Red)
874  MyGame.Sample.Monster.MonsterAddWeapons(builder, weapons)
875  MyGame.Sample.Monster.MonsterAddEquippedType(
876      builder, MyGame.Sample.Equipment.Equipment().Weapon)
877  MyGame.Sample.Monster.MonsterAddEquipped(builder, axe)
878  orc = MyGame.Sample.Monster.MonsterEnd(builder)
879~~~
880</div>
881<div class="language-javascript">
882~~~{.js}
883  // Create our monster by using `startMonster()` and `endMonster()`.
884  MyGame.Sample.Monster.startMonster(builder);
885  MyGame.Sample.Monster.addPos(builder,
886                         MyGame.Sample.Vec3.createVec3(builder, 1.0, 2.0, 3.0));
887  MyGame.Sample.Monster.addHp(builder, 300);
888  MyGame.Sample.Monster.addColor(builder, MyGame.Sample.Color.Red)
889  MyGame.Sample.Monster.addName(builder, name);
890  MyGame.Sample.Monster.addInventory(builder, inv);
891  MyGame.Sample.Monster.addWeapons(builder, weapons);
892  MyGame.Sample.Monster.addEquippedType(builder, MyGame.Sample.Equipment.Weapon);
893  MyGame.Sample.Monster.addEquipped(builder, axe);
894  var orc = MyGame.Sample.Monster.endMonster(builder);
895~~~
896</div>
897<div class="language-php">
898~~~{.php}
899  // Create our monster by using `StartMonster()` and `EndMonster()`.
900  \MyGame\Sample\Monster::StartMonster($builder);
901  \MyGame\Sample\Monster::AddPos($builder,
902                      \MyGame\Sample\Vec3::CreateVec3($builder, 1.0, 2.0, 3.0));
903  \MyGame\Sample\Monster::AddHp($builder, 300);
904  \MyGame\Sample\Monster::AddName($builder, $name);
905  \MyGame\Sample\Monster::AddInventory($builder, $inv);
906  \MyGame\Sample\Monster::AddColor($builder, \MyGame\Sample\Color::Red);
907  \MyGame\Sample\Monster::AddWeapons($builder, $weapons);
908  \MyGame\Sample\Monster::AddEquippedType($builder, \MyGame\Sample\Equipment::Weapon);
909  \MyGame\Sample\Monster::AddEquipped($builder, $axe);
910  $orc = \MyGame\Sample\Monster::EndMonster($builder);
911~~~
912</div>
913<div class="language-c">
914~~~{.c}
915  // Set his hit points to 300 and his mana to 150.
916  uint16_t hp = 300;
917  uint16_t mana = 150;
918
919  // Define an equipment union. `create` calls in C has a single
920  // argument for unions where C++ has both a type and a data argument.
921  ns(Equipment_union_ref_t) equipped = ns(Equipment_as_Weapon(axe));
922  ns(Vec3_t) pos = { 1.0f, 2.0f, 3.0f };
923  ns(Monster_create_as_root(B, &pos, mana, hp, name, inventory, ns(Color_Red),
924          weapons, equipped));
925~~~
926</div>
927
928Note how we create `Vec3` struct in-line in the table. Unlike tables, structs
929are simple combinations of scalars that are always stored inline, just like
930scalars themselves.
931
932**Important**: you should not nest tables or any other objects, which is why
933we created all the strings/vectors/tables that this monster refers to before
934`start`. If you try to create any of them between `start` and `end`, you
935will get an assert/exception/panic depending on your language.
936
937*Note: Since we are passing `150` as the `mana` field, which happens to be the
938default value, the field will not actually be written to the buffer, since the
939default value will be returned on query anyway. This is a nice space savings,
940especially if default values are common in your data. It also means that you do
941not need to be worried of adding a lot of fields that are only used in a small
942number of instances, as it will not bloat the buffer if unused.*
943
944<div class="language-cpp">
945<br>
946If you do not wish to set every field in a `table`, it may be more convenient to
947manually set each field of your monster, instead of calling `CreateMonster()`.
948The following snippet is functionally equivalent to the above code, but provides
949a bit more flexibility.
950<br>
951~~~{.cpp}
952  // You can use this code instead of `CreateMonster()`, to create our orc
953  // manually.
954  MonsterBuilder monster_builder(builder);
955  monster_builder.add_pos(&pos);
956  monster_builder.add_hp(hp);
957  monster_builder.add_name(name);
958  monster_builder.add_inventory(inventory);
959  monster_builder.add_color(Color_Red);
960  monster_builder.add_weapons(weapons);
961  monster_builder.add_equipped_type(Equipment_Weapon);
962  monster_builder.add_equpped(axe);
963  auto orc = monster_builder.Finish();
964~~~
965</div>
966<div class="language-c">
967If you do not wish to set every field in a `table`, it may be more convenient to
968manually set each field of your monster, instead of calling `create_monster_as_root()`.
969The following snippet is functionally equivalent to the above code, but provides
970a bit more flexibility.
971<br>
972~~~{.c}
973  // It is important to pair `start_as_root` with `end_as_root`.
974  ns(Monster_start_as_root(B));
975  ns(Monster_pos_create(B, 1.0f, 2.0f, 3.0f));
976  // or alternatively
977  //ns(Monster_pos_add(&pos);
978
979  ns(Monster_hp_add(B, hp));
980  // Notice that `Monser_name_add` adds a string reference unlike the
981  // add_str and add_strn variants.
982  ns(Monster_name_add(B, name));
983  ns(Monster_inventory_add(B, inventory));
984  ns(Monster_color_add(B, ns(Color_Red)));
985  ns(Monster_weapons_add(B, weapons));
986  ns(Monster_equipped_add(B, equipped));
987  // Complete the monster object and make it the buffer root object.
988  ns(Monster_end_as_root(B));
989~~~
990</div>
991
992Before finishing the serialization, let's take a quick look at FlatBuffer
993`union Equipped`. There are two parts to each FlatBuffer `union`. The first, is
994a hidden field `_type`, that is generated to hold the type of `table` referred
995to by the `union`. This allows you to know which type to cast to at runtime.
996Second, is the `union`'s data.
997
998In our example, the last two things we added to our `Monster` were the
999`Equipped Type` and the `Equipped` union itself.
1000
1001Here is a repetition these lines, to help highlight them more clearly:
1002
1003<div class="language-cpp">
1004  ~~~{.cpp}
1005    monster_builder.add_equipped_type(Equipment_Weapon); // Union type
1006    monster_builder.add_equipped(axe); // Union data
1007  ~~~
1008</div>
1009<div class="language-java">
1010  ~~~{.java}
1011    Monster.addEquippedType(builder, Equipment.Weapon); // Union type
1012    Monster.addEquipped(axe); // Union data
1013  ~~~
1014</div>
1015<div class="language-csharp">
1016  ~~~{.cs}
1017    Monster.AddEquippedType(builder, Equipment.Weapon); // Union type
1018    Monster.AddEquipped(builder, axe.Value); // Union data
1019  ~~~
1020</div>
1021<div class="language-go">
1022  ~~~{.go}
1023    sample.MonsterAddEquippedType(builder, sample.EquipmentWeapon) // Union type
1024    sample.MonsterAddEquipped(builder, axe) // Union data
1025  ~~~
1026</div>
1027<div class="language-python">
1028  ~~~{.py}
1029    MyGame.Sample.Monster.MonsterAddEquippedType(            # Union type
1030        builder, MyGame.Sample.Equipment.Equipment().Weapon)
1031    MyGame.Sample.Monster.MonsterAddEquipped(builder, axe)   # Union data
1032  ~~~
1033</div>
1034<div class="language-javascript">
1035  ~~~{.js}
1036    MyGame.Sample.Monster.addEquippedType(builder, MyGame.Sample.Equipment.Weapon); // Union type
1037    MyGame.Sample.Monster.addEquipped(builder, axe); // Union data
1038  ~~~
1039</div>
1040<div class="language-php">
1041  ~~~{.php}
1042    \MyGame\Sample\Monster::AddEquippedType($builder, \MyGame\Sample\Equipment::Weapon); // Union type
1043    \MyGame\Sample\Monster::AddEquipped($builder, $axe); // Union data
1044  ~~~
1045</div>
1046<div class="language-c">
1047~~~{.c}
1048  // Add union type and data simultanously.
1049  ns(Monster_equipped_Weapon_add(B, axe));
1050~~~
1051</div>
1052
1053After you have created your buffer, you will have the offset to the root of the
1054data in the `orc` variable, so you can finish the buffer by calling the
1055appropriate `finish` method.
1056
1057
1058<div class="language-cpp">
1059~~~{.cpp}
1060  // Call `Finish()` to instruct the builder that this monster is complete.
1061  // Note: Regardless of how you created the `orc`, you still need to call
1062  // `Finish()` on the `FlatBufferBuilder`.
1063  builder.Finish(orc); // You could also call `FinishMonsterBuffer(builder,
1064                       //                                          orc);`.
1065~~~
1066</div>
1067<div class="language-java">
1068~~~{.java}
1069  // Call `finish()` to instruct the builder that this monster is complete.
1070  builder.finish(orc); // You could also call `Monster.finishMonsterBuffer(builder, orc);`.
1071~~~
1072</div>
1073<div class="language-csharp">
1074~~~{.cs}
1075  // Call `Finish()` to instruct the builder that this monster is complete.
1076  builder.Finish(orc.Value); // You could also call `Monster.FinishMonsterBuffer(builder, orc);`.
1077~~~
1078</div>
1079<div class="language-go">
1080~~~{.go}
1081  // Call `Finish()` to instruct the builder that this monster is complete.
1082  builder.Finish(orc)
1083~~~
1084</div>
1085<div class="language-python">
1086~~~{.py}
1087  # Call `Finish()` to instruct the builder that this monster is complete.
1088  builder.Finish(orc)
1089~~~
1090</div>
1091<div class="language-javascript">
1092~~~{.js}
1093  // Call `finish()` to instruct the builder that this monster is complete.
1094  builder.finish(orc); // You could also call `MyGame.Example.Monster.finishMonsterBuffer(builder,
1095                       //                                                                 orc);`.
1096~~~
1097</div>
1098<div class="language-php">
1099~~~{.php}
1100  // Call `finish()` to instruct the builder that this monster is complete.
1101   $builder->finish($orc); // You may also call `\MyGame\Sample\Monster::FinishMonsterBuffer(
1102                           //                        $builder, $orc);`.
1103~~~
1104</div>
1105<div class="language-c">
1106~~~{.c}
1107  // Because we used `Monster_create_as_root`, we do not need a `finish` call in C`.
1108~~~
1109</div>
1110
1111The buffer is now ready to be stored somewhere, sent over the network, be
1112compressed, or whatever you'd like to do with it. You can access the buffer
1113like so:
1114
1115<div class="language-cpp">
1116~~~{.cpp}
1117  // This must be called after `Finish()`.
1118  uint8_t *buf = builder.GetBufferPointer();
1119  int size = builder.GetSize(); // Returns the size of the buffer that
1120                                // `GetBufferPointer()` points to.
1121~~~
1122</div>
1123<div class="language-java">
1124~~~{.java}
1125  // This must be called after `finish()`.
1126  java.nio.ByteBuffer buf = builder.dataBuffer();
1127  // The data in this ByteBuffer does NOT start at 0, but at buf.position().
1128  // The number of bytes is buf.remaining().
1129
1130  // Alternatively this copies the above data out of the ByteBuffer for you:
1131  bytes[] buf = builder.sizedByteArray();
1132~~~
1133</div>
1134<div class="language-csharp">
1135~~~{.cs}
1136  // This must be called after `Finish()`.
1137  var buf = builder.DataBuffer; // Of type `FlatBuffers.ByteBuffer`.
1138  // The data in this ByteBuffer does NOT start at 0, but at buf.Position.
1139  // The end of the data is marked by buf.Length, so the size is
1140  // buf.Length - buf.Position.
1141
1142  // Alternatively this copies the above data out of the ByteBuffer for you:
1143  bytes[] buf = builder.SizedByteArray();
1144~~~
1145</div>
1146<div class="language-go">
1147~~~{.go}
1148  // This must be called after `Finish()`.
1149  buf := builder.FinishedBytes() // Of type `byte[]`.
1150~~~
1151</div>
1152<div class="language-python">
1153~~~{.py}
1154  # This must be called after `Finish()`.
1155  buf = builder.Output() // Of type `bytearray`.
1156~~~
1157</div>
1158<div class="language-javascript">
1159~~~{.js}
1160  // This must be called after `finish()`.
1161  var buf = builder.asUint8Array(); // Of type `Uint8Array`.
1162~~~
1163</div>
1164<div class="language-php">
1165~~~{.php}
1166  // This must be called after `finish()`.
1167  $buf = $builder->dataBuffer(); // Of type `Google\FlatBuffers\ByteBuffer`
1168  // The data in this ByteBuffer does NOT start at 0, but at buf->getPosition().
1169  // The end of the data is marked by buf->capacity(), so the size is
1170  // buf->capacity() - buf->getPosition().
1171~~~
1172</div>
1173<div class="language-c">
1174~~~{.c}
1175  uint8_t *buf;
1176  size_t size;
1177
1178  // Allocate and extract a readable buffer from internal builder heap.
1179  // The returned buffer must be deallocated using `free`.
1180  // NOTE: Finalizing the buffer does NOT change the builder, it
1181  // just creates a snapshot of the builder content.
1182  buf = flatcc_builder_finalize_buffer(B, &size);
1183  // use buf
1184  free(buf);
1185
1186  // Optionally reset builder to reuse builder without deallocating
1187  // internal stack and heap.
1188  flatcc_builder_reset(B);
1189  // build next buffer.
1190  // ...
1191
1192  // Cleanup.
1193  flatcc_builder_clear(B);
1194~~~
1195</div>
1196
1197Now you can write the bytes to a file, send them over the network..
1198**Make sure your file mode (or tranfer protocol) is set to BINARY, not text.**
1199If you transfer a FlatBuffer in text mode, the buffer will be corrupted,
1200which will lead to hard to find problems when you read the buffer.
1201
1202#### Reading Orc FlatBuffers
1203
1204Now that we have successfully created an `Orc` FlatBuffer, the monster data can
1205be saved, sent over a network, etc. Let's now adventure into the inverse, and
1206deserialize a FlatBuffer.
1207
1208This section requires the same import/include, namespace, etc. requirements as
1209before:
1210
1211<div class="language-cpp">
1212~~~{.cpp}
1213  #include "monster_generate.h" // This was generated by `flatc`.
1214
1215  using namespace MyGame::Sample; // Specified in the schema.
1216~~~
1217</div>
1218<div class="language-java">
1219~~~{.java}
1220  import MyGame.Sample.*; //The `flatc` generated files. (Monster, Vec3, etc.)
1221
1222  import com.google.flatbuffers.FlatBufferBuilder;
1223~~~
1224</div>
1225<div class="language-csharp">
1226~~~{.cs}
1227  using FlatBuffers;
1228  using MyGame.Sample; // The `flatc` generated files. (Monster, Vec3, etc.)
1229~~~
1230</div>
1231<div class="language-go">
1232~~~{.go}
1233  import (
1234          flatbuffers "github.com/google/flatbuffers/go"
1235          sample "MyGame/Sample"
1236  )
1237~~~
1238</div>
1239<div class="language-python">
1240~~~{.py}
1241  import flatbuffers
1242
1243  # Generated by `flatc`.
1244  import MyGame.Sample.Any
1245  import MyGame.Sample.Color
1246  import MyGame.Sample.Monster
1247  import MyGame.Sample.Vec3
1248~~~
1249</div>
1250<div class="language-javascript">
1251~~~{.js}
1252  // The following code is for JavaScript module loaders (e.g. Node.js). See
1253  // below for a browser-based HTML/JavaScript example of including the library.
1254  var flatbuffers = require('/js/flatbuffers').flatbuffers;
1255  var MyGame = require('./monster_generated').MyGame; // Generated by `flatc`.
1256
1257  //--------------------------------------------------------------------------//
1258
1259  // The following code is for browser-based HTML/JavaScript. Use the above code
1260  // for JavaScript module loaders (e.g. Node.js).
1261  <script src="../js/flatbuffers.js"></script>
1262  <script src="monster_generated.js"></script> // Generated by `flatc`.
1263~~~
1264</div>
1265<div class="language-php">
1266~~~{.php}
1267  // It is recommended that your use PSR autoload when using FlatBuffers in PHP.
1268  // Here is an example from `SampleBinary.php`:
1269  function __autoload($class_name) {
1270    // The last segment of the class name matches the file name.
1271    $class = substr($class_name, strrpos($class_name, "\\") + 1);
1272    $root_dir = join(DIRECTORY_SEPARATOR, array(dirname(dirname(__FILE__)))); // `flatbuffers` root.
1273
1274    // Contains the `*.php` files for the FlatBuffers library and the `flatc` generated files.
1275    $paths = array(join(DIRECTORY_SEPARATOR, array($root_dir, "php")),
1276                   join(DIRECTORY_SEPARATOR, array($root_dir, "samples", "MyGame", "Sample")));
1277    foreach ($paths as $path) {
1278      $file = join(DIRECTORY_SEPARATOR, array($path, $class . ".php"));
1279      if (file_exists($file)) {
1280        require($file);
1281        break;
1282      }
1283    }
1284  }
1285~~~
1286</div>
1287<div class="language-c">
1288~~~{.c}
1289  // Only needed if we don't have `#include "monster_builder.h"`.
1290  #include "monster_reader.h"
1291
1292  #undef ns
1293  #define ns(x) FLATBUFFERS_WRAP_NAMESPACE(MyGame_Sample, x) // Specified in the schema.
1294~~~
1295</div>
1296
1297Then, assuming you have a buffer of bytes received from disk,
1298network, etc., you can create start accessing the buffer like so:
1299
1300**Again, make sure you read the bytes in BINARY mode, otherwise the code below
1301won't work**
1302
1303<div class="language-cpp">
1304~~~{.cpp}
1305  uint8_t *buffer_pointer = /* the data you just read */;
1306
1307  // Get a pointer to the root object inside the buffer.
1308  auto monster = GetMonster(buffer_pointer);
1309
1310  // `monster` is of type `Monster *`.
1311  // Note: root object pointers are NOT the same as `buffer_pointer`.
1312~~~
1313</div>
1314<div class="language-java">
1315~~~{.java}
1316  byte[] bytes = /* the data you just read */
1317  java.nio.ByteBuffer buf = java.nio.ByteBuffer.wrap(bytes);
1318
1319  // Get an accessor to the root object inside the buffer.
1320  Monster monster = Monster.getRootAsMonster(buf);
1321~~~
1322</div>
1323<div class="language-csharp">
1324~~~{.cs}
1325  byte[] bytes = /* the data you just read */
1326  var buf = new ByteBuffer(bytes);
1327
1328  // Get an accessor to the root object inside the buffer.
1329  var monster = Monster.GetRootAsMonster(buf);
1330~~~
1331</div>
1332<div class="language-go">
1333~~~{.go}
1334  var buf []byte = /* the data you just read */
1335
1336  // Get an accessor to the root object inside the buffer.
1337  monster := sample.GetRootAsMonster(buf, 0)
1338
1339  // Note: We use `0` for the offset here, which is typical for most buffers
1340  // you would read. If you wanted to read from `builder.Bytes` directly, you
1341  // would need to pass in the offset of `builder.Head()`, as the builder
1342  // constructs the buffer backwards, so may not start at offset 0.
1343~~~
1344</div>
1345<div class="language-python">
1346~~~{.py}
1347  buf = /* the data you just read, in an object of type "bytearray" */
1348
1349  // Get an accessor to the root object inside the buffer.
1350  monster = MyGame.Sample.Monster.Monster.GetRootAsMonster(buf, 0)
1351
1352  # Note: We use `0` for the offset here, which is typical for most buffers
1353  # you would read.  If you wanted to read from the `builder.Bytes` directly,
1354  # you would need to pass in the offset of `builder.Head()`, as the builder
1355  # constructs the buffer backwards, so may not start at offset 0.
1356~~~
1357</div>
1358<div class="language-javascript">
1359~~~{.js}
1360  var bytes = /* the data you just read, in an object of type "Uint8Array" */
1361  var buf = new flatbuffers.ByteBuffer(bytes);
1362
1363  // Get an accessor to the root object inside the buffer.
1364  var monster = MyGame.Sample.Monster.getRootAsMonster(buf);
1365~~~
1366</div>
1367<div class="language-php">
1368~~~{.php}
1369  $bytes = /* the data you just read, in a string */
1370  $buf = Google\FlatBuffers\ByteBuffer::wrap($bytes);
1371
1372  // Get an accessor to the root object inside the buffer.
1373  $monster = \MyGame\Sample\Monster::GetRootAsMonster($buf);
1374~~~
1375</div>
1376<div class="language-c">
1377~~~{.c}
1378  // Note that we use the `table_t` suffix when reading a table object
1379  // as opposed to the `ref_t` suffix used during the construction of
1380  // the buffer.
1381  ns(Monster_table_t) monster = ns(Monster_as_root(buffer));
1382
1383  // Note: root object pointers are NOT the same as the `buffer` pointer.
1384~~~
1385</div>
1386
1387If you look in the generated files from the schema compiler, you will see it generated
1388accessors for all non-`deprecated` fields. For example:
1389
1390<div class="language-cpp">
1391~~~{.cpp}
1392  auto hp = monster->hp();
1393  auto mana = monster->mana();
1394  auto name = monster->name()->c_str();
1395~~~
1396</div>
1397<div class="language-java">
1398~~~{.java}
1399  short hp = monster.hp();
1400  short mana = monster.mana();
1401  String name = monster.name();
1402~~~
1403</div>
1404<div class="language-csharp">
1405~~~{.cs}
1406  // For C#, unlike other languages support by FlatBuffers, most values (except for
1407  // vectors and unions) are available as propreties instead of asccessor methods.
1408  var hp = monster.Hp
1409  var mana = monster.Mana
1410  var name = monster.Name
1411~~~
1412</div>
1413<div class="language-go">
1414~~~{.go}
1415  hp := monster.Hp()
1416  mana := monster.Mana()
1417  name := string(monster.Name()) // Note: `monster.Name()` returns a byte[].
1418~~~
1419</div>
1420<div class="language-python">
1421~~~{.py}
1422  hp = monster.Hp()
1423  mana = monster.Mana()
1424  name = monster.Name()
1425~~~
1426</div>
1427<div class="language-javascript">
1428~~~{.js}
1429  var hp = $monster.hp();
1430  var mana = $monster.mana();
1431  var name = $monster.name();
1432~~~
1433</div>
1434<div class="language-php">
1435~~~{.php}
1436  $hp = $monster->getHp();
1437  $mana = $monster->getMana();
1438  $name = monster->getName();
1439~~~
1440</div>
1441<div class="language-c">
1442~~~{.c}
1443  uint16_t hp = ns(Monster_hp(monster));
1444  uint16_t mana = ns(Monster_mana(monster));
1445  flatbuffers_string_t name = ns(Monster_name(monster));
1446~~~
1447</div>
1448
1449These should hold `300`, `150`, and `"Orc"` respectively.
1450
1451*Note: The default value `150` wasn't stored in `mana`, but we are still able to retrieve it.*
1452
1453To access sub-objects, in the case of our `pos`, which is a `Vec3`:
1454
1455<div class="language-cpp">
1456~~~{.cpp}
1457  auto pos = monster->pos();
1458  auto x = pos->x();
1459  auto y = pos->y();
1460  auto z = pos->z();
1461~~~
1462</div>
1463<div class="language-java">
1464~~~{.java}
1465  Vec3 pos = monster.pos();
1466  float x = pos.x();
1467  float y = pos.y();
1468  float z = pos.z();
1469~~~
1470</div>
1471<div class="language-csharp">
1472~~~{.cs}
1473  var pos = monster.Pos
1474  var x = pos.X
1475  var y = pos.Y
1476  var z = pos.Z
1477~~~
1478</div>
1479<div class="language-go">
1480~~~{.go}
1481  pos := monster.Pos(nil)
1482  x := pos.X()
1483  y := pos.Y()
1484  z := pos.Z()
1485
1486  // Note: Whenever you access a new object, like in `Pos()`, a new temporary
1487  // accessor object gets created. If your code is very performance sensitive,
1488  // you can pass in a pointer to an existing `Vec3` instead of `nil`. This
1489  // allows you to reuse it across many calls to reduce the amount of object
1490  // allocation/garbage collection.
1491~~~
1492</div>
1493<div class="language-python">
1494~~~{.py}
1495  pos = monster.Pos()
1496  x = pos.X()
1497  y = pos.Y()
1498  z = pos.Z()
1499~~~
1500</div>
1501<div class="language-javascript">
1502~~~{.js}
1503  var pos = monster.pos();
1504  var x = pos.x();
1505  var y = pos.y();
1506  var z = pos.z();
1507~~~
1508</div>
1509<div class="language-php">
1510~~~{.php}
1511  $pos = $monster->getPos();
1512  $x = $pos->getX();
1513  $y = $pos->getY();
1514  $z = $pos->getZ();
1515~~~
1516</div>
1517<div class="language-c">
1518~~~{.c}
1519  ns(Vec3_struct_t) pos = ns(Monster_pos(monster));
1520  float x = ns(Vec3_x(pos));
1521  float y = ns(Vec3_y(pos));
1522  float z = ns(Vec3_z(pos));
1523~~~
1524</div>
1525
1526`x`, `y`, and `z` will contain `1.0`, `2.0`, and `3.0`, respectively.
1527
1528*Note: Had we not set `pos` during serialization, it would be a `NULL`-value.*
1529
1530Similarly, we can access elements of the inventory `vector` by indexing it. You
1531can also iterate over the length of the array/vector representing the
1532FlatBuffers `vector`.
1533
1534<div class="language-cpp">
1535~~~{.cpp}
1536  auto inv = monster->inventory(); // A pointer to a `flatbuffers::Vector<>`.
1537  auto inv_len = inv->Length();
1538  auto third_item = inv->Get(2);
1539~~~
1540</div>
1541<div class="language-java">
1542~~~{.java}
1543  int invLength = monster.inventoryLength();
1544  byte thirdItem = monster.inventory(2);
1545~~~
1546</div>
1547<div class="language-csharp">
1548~~~{.cs}
1549  int invLength = monster.InventoryLength;
1550  var thirdItem = monster.GetInventory(2);
1551~~~
1552</div>
1553<div class="language-go">
1554~~~{.go}
1555  invLength := monster.InventoryLength()
1556  thirdItem := monster.Inventory(2)
1557~~~
1558</div>
1559<div class="language-python">
1560~~~{.py}
1561  inv_len = monster.InventoryLength()
1562  third_item = monster.Inventory(2)
1563~~~
1564</div>
1565<div class="language-javascript">
1566~~~{.js}
1567  var invLength = monster.inventoryLength();
1568  var thirdItem = monster.inventory(2);
1569~~~
1570</div>
1571<div class="language-php">
1572~~~{.php}
1573  $inv_len = $monster->getInventoryLength();
1574  $third_item = $monster->getInventory(2);
1575~~~
1576</div>
1577<div class="language-c">
1578~~~{.c}
1579    // If `inv` hasn't been set, it will be null. It is valid get
1580    // the length of null which will be 0, useful for iteration.
1581    flatbuffers_uint8_vec_t inv = ns(Monster_inventory(monster));
1582    size_t inv_len = flatbuffers_uint8_vec_len(inv);
1583~~~
1584</div>
1585
1586For `vector`s of `table`s, you can access the elements like any other vector,
1587except your need to handle the result as a FlatBuffer `table`:
1588
1589<div class="language-cpp">
1590~~~{.cpp}
1591  auto weapons = monster->weapons(); // A pointer to a `flatbuffers::Vector<>`.
1592  auto weapon_len = weapons->Length();
1593  auto second_weapon_name = weapons->Get(1)->name()->str();
1594  auto second_weapon_damage = weapons->Get(1)->damage()
1595~~~
1596</div>
1597<div class="language-java">
1598~~~{.java}
1599  int weaponsLength = monster.weaponsLength();
1600  String secondWeaponName = monster.weapons(1).name();
1601  short secondWeaponDamage = monster.weapons(1).damage();
1602~~~
1603</div>
1604<div class="language-csharp">
1605~~~{.cs}
1606  int weaponsLength = monster.WeaponsLength;
1607  var secondWeaponName = monster.GetWeapons(1).Name;
1608  var secondWeaponDamage = monster.GetWeapons(1).Damage;
1609~~~
1610</div>
1611<div class="language-go">
1612~~~{.go}
1613  weaponLength := monster.WeaponsLength()
1614  weapon := new(sample.Weapon) // We need a `sample.Weapon` to pass into `monster.Weapons()`
1615                               // to capture the output of the function.
1616  if monster.Weapons(weapon, 1) {
1617          secondWeaponName := weapon.Name()
1618          secondWeaponDamage := weapon.Damage()
1619  }
1620~~~
1621</div>
1622<div class="language-python">
1623~~~{.py}
1624  weapons_length = monster.WeaponsLength()
1625  second_weapon_name = monster.Weapons(1).Name()
1626  second_weapon_damage = monster.Weapons(1).Damage()
1627~~~
1628</div>
1629<div class="language-javascript">
1630~~~{.js}
1631  var weaponsLength = monster.weaponsLength();
1632  var secondWeaponName = monster.weapons(1).name();
1633  var secondWeaponDamage = monster.weapons(1).damage();
1634~~~
1635</div>
1636<div class="language-php">
1637~~~{.php}
1638  $weapons_len = $monster->getWeaponsLength();
1639  $second_weapon_name = $monster->getWeapons(1)->getName();
1640  $second_weapon_damage = $monster->getWeapons(1)->getDamage();
1641~~~
1642</div>
1643<div class="language-c">
1644~~~{.c}
1645  ns(Weapon_vec_t) weapons = ns(Monster_weapons(monster));
1646  size_t weapons_len = ns(Weapon_vec_len(weapons));
1647  // We can use `const char *` instead of `flatbuffers_string_t`.
1648  const char *second_weapon_name = ns(Weapon_name(ns(Weapon_vec_at(weapons, 1))));
1649  uint16_t second_weapon_damage =  ns(Weapon_damage(ns(Weapon_vec_at(weapons, 1))));
1650~~~
1651</div>
1652
1653Last, we can access our `Equipped` FlatBuffer `union`. Just like when we created
1654the `union`, we need to get both parts of the `union`: the type and the data.
1655
1656We can access the type to dynamically cast the data as needed (since the
1657`union` only stores a FlatBuffer `table`).
1658
1659<div class="language-cpp">
1660~~~{.cpp}
1661  auto union_type = monster.equipped_type();
1662
1663  if (union_type == Equipment_Weapon) {
1664    auto weapon = static_cast<const Weapon*>(monster->equipped()); // Requires `static_cast`
1665                                                                   // to type `const Weapon*`.
1666
1667    auto weapon_name = weapon->name()->str(); // "Axe"
1668    auto weapon_damage = weapon->damage();    // 5
1669  }
1670~~~
1671</div>
1672<div class="language-java">
1673~~~{.java}
1674  int unionType = monster.EquippedType();
1675
1676  if (unionType == Equipment.Weapon) {
1677    Weapon weapon = (Weapon)monster.equipped(new Weapon()); // Requires explicit cast
1678                                                            // to `Weapon`.
1679
1680    String weaponName = weapon.name();    // "Axe"
1681    short weaponDamage = weapon.damage(); // 5
1682  }
1683~~~
1684</div>
1685<div class="language-csharp">
1686~~~{.cs}
1687  var unionType = monster.EquippedType;
1688
1689  if (unionType == Equipment.Weapon) {
1690    var weapon = (Weapon)monster.GetEquipped(new Weapon()); // Requires explicit cast
1691                                                            // to `Weapon`.
1692
1693    var weaponName = weapon.Name;     // "Axe"
1694    var weaponDamage = weapon.Damage; // 5
1695  }
1696~~~
1697</div>
1698<div class="language-go">
1699~~~{.go}
1700  // We need a `flatbuffers.Table` to capture the output of the
1701  // `monster.Equipped()` function.
1702  unionTable := new(flatbuffers.Table)
1703
1704  if monster.Equipped(unionTable) {
1705          unionType := monster.EquippedType()
1706
1707          if unionType == sample.EquipmentWeapon {
1708                  // Create a `sample.Weapon` object that can be initialized with the contents
1709                  // of the `flatbuffers.Table` (`unionTable`), which was populated by
1710                  // `monster.Equipped()`.
1711                  unionWeapon = new(sample.Weapon)
1712                  unionWeapon.Init(unionTable.Bytes, unionTable.Pos)
1713
1714                  weaponName = unionWeapon.Name()
1715                  weaponDamage = unionWeapon.Damage()
1716          }
1717  }
1718~~~
1719</div>
1720<div class="language-python">
1721~~~{.py}
1722  union_type = monster.EquippedType()
1723
1724  if union_type == MyGame.Sample.Equipment.Equipment().Weapon:
1725    # `monster.Equipped()` returns a `flatbuffers.Table`, which can be used to
1726    # initialize a `MyGame.Sample.Weapon.Weapon()`.
1727    union_weapon = MyGame.Sample.Weapon.Weapon()
1728    union_weapon.Init(monster.Equipped().Bytes, monster.Equipped().Pos)
1729
1730    weapon_name = union_weapon.Name()     // 'Axe'
1731    weapon_damage = union_weapon.Damage() // 5
1732~~~
1733</div>
1734<div class="language-javascript">
1735~~~{.js}
1736  var unionType = monster.equippedType();
1737
1738  if (unionType == MyGame.Sample.Equipment.Weapon) {
1739    var weapon_name = monster.equipped(new MyGame.Sample.Weapon()).name();     // 'Axe'
1740    var weapon_damage = monster.equipped(new MyGame.Sample.Weapon()).damage(); // 5
1741  }
1742~~~
1743</div>
1744<div class="language-php">
1745~~~{.php}
1746  $union_type = $monster->getEquippedType();
1747
1748  if ($union_type == \MyGame\Sample\Equipment::Weapon) {
1749    $weapon_name = $monster->getEquipped(new \MyGame\Sample\Weapon())->getName();     // "Axe"
1750    $weapon_damage = $monster->getEquipped(new \MyGame\Sample\Weapon())->getDamage(); // 5
1751  }
1752~~~
1753</div>
1754<div class="language-c">
1755~~~{.c}
1756  // Access union type field.
1757  if (ns(Monster_equipped_type(monster)) == ns(Equipment_Weapon)) {
1758      // Cast to appropriate type:
1759      // C allows for silent void pointer assignment, so we need no explicit cast.
1760      ns(Weapon_table_t) weapon = ns(Monster_equipped(monster));
1761      const char *weapon_name = ns(Weapon_name(weapon)); // "Axe"
1762      uint16_t weapon_damage = ns(Weapon_damage(weapon)); // 5
1763  }
1764~~~
1765</div>
1766
1767## Mutating FlatBuffers
1768
1769As you saw above, typically once you have created a FlatBuffer, it is read-only
1770from that moment on. There are, however, cases where you have just received a
1771FlatBuffer, and you'd like to modify something about it before sending it on to
1772another recipient. With the above functionality, you'd have to generate an
1773entirely new FlatBuffer, while tracking what you modified in your own data
1774structures. This is inconvenient.
1775
1776For this reason FlatBuffers can also be mutated in-place. While this is great
1777for making small fixes to an existing buffer, you generally want to create
1778buffers from scratch whenever possible, since it is much more efficient and the
1779API is much more general purpose.
1780
1781To get non-const accessors, invoke `flatc` with `--gen-mutable`.
1782
1783Similar to how we read fields using the accessors above, we can now use the
1784mutators like so:
1785
1786<div class="language-cpp">
1787~~~{.cpp}
1788  auto monster = GetMutableMonster(buffer_pointer);  // non-const
1789  monster->mutate_hp(10);                      // Set the table `hp` field.
1790  monster->mutable_pos()->mutate_z(4);         // Set struct field.
1791  monster->mutable_inventory()->Mutate(0, 1);  // Set vector element.
1792~~~
1793</div>
1794<div class="language-java">
1795~~~{.java}
1796  Monster monster = Monster.getRootAsMonster(buf);
1797  monster.mutateHp(10);            // Set table field.
1798  monster.pos().mutateZ(4);        // Set struct field.
1799  monster.mutateInventory(0, 1);   // Set vector element.
1800~~~
1801</div>
1802<div class="language-csharp">
1803~~~{.cs}
1804  var monster = Monster.GetRootAsMonster(buf);
1805  monster.MutateHp(10);            // Set table field.
1806  monster.Pos.MutateZ(4);          // Set struct field.
1807  monster.MutateInventory(0, 1);   // Set vector element.
1808~~~
1809</div>
1810<div class="language-go">
1811~~~{.go}
1812  <API for mutating FlatBuffers is not yet available in Go.>
1813~~~
1814</div>
1815<div class="language-python">
1816~~~{.py}
1817  <API for mutating FlatBuffers is not yet available in Python.>
1818~~~
1819</div>
1820<div class="language-javascript">
1821~~~{.js}
1822  <API for mutating FlatBuffers is not yet support in JavaScript.>
1823~~~
1824</div>
1825<div class="language-php">
1826~~~{.php}
1827  <API for mutating FlatBuffers is not yet supported in PHP.>
1828~~~
1829</div>
1830<div class="language-c">
1831~~~{.c}
1832  <API for in-place mutating FlatBuffers will not be supported in C
1833  (except in-place vector sorting is possible).>
1834~~~
1835</div>
1836
1837We use the somewhat verbose term `mutate` instead of `set` to indicate that this
1838is a special use case, not to be confused with the default way of constructing
1839FlatBuffer data.
1840
1841After the above mutations, you can send on the FlatBuffer to a new recipient
1842without any further work!
1843
1844Note that any `mutate` functions on a table will return a boolean, which is
1845`false` if the field we're trying to set is not present in the buffer. Fields
1846that are not present if they weren't set, or even if they happen to be equal to
1847the default value. For example, in the creation code above, the `mana`
1848field is equal to `150`, which is the default value, so it was never stored in
1849the buffer. Trying to call the corresponding `mutate` method for `mana` on such
1850data will return `false`, and the value won't actually be modified!
1851
1852One way to solve this is to call `ForceDefaults` on a FlatBufferBuilder to
1853force all fields you set to actually be written. This, of course, increases the
1854size of the buffer somewhat, but this may be acceptable for a mutable buffer.
1855
1856If this is not sufficient, other ways of mutating FlatBuffers may be supported
1857in your language through an object based API (`--gen-object-api`) or reflection.
1858See the individual language documents for support.
1859
1860## JSON with FlatBuffers
1861
1862#### Using `flatc` as a Conversion Tool
1863
1864This is often the preferred method to use JSON with FlatBuffers, as it doesn't
1865require you to add any new code to your program. It is also efficient, since you
1866can ship with the binary data. The drawback is that it requires an extra step
1867for your users/developers to perform (although it may be able to be automated
1868as part of your compilation).
1869
1870Lets say you have a JSON file that describes your monster. In this example,
1871we will use the file `flatbuffers/samples/monsterdata.json`.
1872
1873Here are the contents of the file:
1874
1875~~~{.json}
1876{
1877  pos: {
1878    x: 1,
1879    y: 2,
1880    z: 3
1881  },
1882  hp: 300,
1883  name: "Orc"
1884}
1885~~~
1886
1887You can run this file through the `flatc` compile with the `-b` flag and
1888our `monster.fbs` schema to produce a FlatBuffer binary file.
1889
1890~~~{.sh}
1891./../flatc -b monster.fbs monsterdata.json
1892~~~
1893
1894The output of this will be a file `monsterdata.bin`, which will contain the
1895FlatBuffer binary representation of the contents from our `.json` file.
1896
1897<div class="language-cpp">
1898*Note: If you're working in C++, you can also parse JSON at runtime. See the
1899[Use in C++](@ref flatbuffers_guide_use_cpp) section of the Programmer's
1900Guide for more information.*
1901</div>
1902<div class="language-c">
1903*Note: If you're working in C, the `flatcc --json` (not `flatc`)
1904compiler will generate schema specific high performance json parsers and
1905printers that you can compile and use at runtime. The `flatc` compiler (not
1906`flatcc`) on the other hand, is still useful for general offline json to
1907flatbuffer conversion from a given schema. There are no current plans
1908for `flatcc` to support this.*
1909</div>
1910
1911## Advanced Features for Each Language
1912
1913Each language has a dedicated `Use in XXX` page in the Programmer's Guide
1914to cover the nuances of FlatBuffers in that language.
1915
1916For your chosen language, see:
1917
1918<div class="language-cpp">
1919[Use in C++](@ref flatbuffers_guide_use_cpp)
1920</div>
1921<div class="language-java">
1922[Use in Java/C#](@ref flatbuffers_guide_use_java_c-sharp)
1923</div>
1924<div class="language-csharp">
1925[Use in Java/C#](@ref flatbuffers_guide_use_java_c-sharp)
1926</div>
1927<div class="language-go">
1928[Use in Go](@ref flatbuffers_guide_use_go)
1929</div>
1930<div class="language-python">
1931[Use in Python](@ref flatbuffers_guide_use_python)
1932</div>
1933<div class="language-javascript">
1934[Use in JavaScript](@ref flatbuffers_guide_use_javascript)
1935</div>
1936<div class="language-php">
1937[Use in PHP](@ref flatbuffers_guide_use_php)
1938</div>
1939<div class="language-c">
1940[Use in C](@ref flatbuffers_guide_use_c)
1941</div>
1942
1943<br>
1944