| <!-- HTML header for doxygen 1.8.6--> |
| <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> |
| <html xmlns="http://www.w3.org/1999/xhtml"> |
| <head> |
| <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> |
| <meta http-equiv="X-UA-Compatible" content="IE=9"/> |
| <meta name="generator" content="Doxygen 1.9.1"/> |
| <title>FlatBuffers: Use in C#</title> |
| <link href="tabs.css" rel="stylesheet" type="text/css"/> |
| <script type="text/javascript" src="jquery.js"></script> |
| <script type="text/javascript" src="dynsections.js"></script> |
| <link href="navtree.css" rel="stylesheet" type="text/css"/> |
| <script type="text/javascript" src="resize.js"></script> |
| <script type="text/javascript" src="navtreedata.js"></script> |
| <script type="text/javascript" src="navtree.js"></script> |
| <link href="search/search.css" rel="stylesheet" type="text/css"/> |
| <script type="text/javascript" src="search/searchdata.js"></script> |
| <script type="text/javascript" src="search/search.js"></script> |
| <link href="doxygen.css" rel="stylesheet" type="text/css" /> |
| <link href="https://fonts.googleapis.com/css?family=Roboto:300,400,400italic,500,500italic,700,700italic|Roboto+Mono:400,700" rel="stylesheet"> |
| <link href="style.css" rel="stylesheet" type="text/css"/> |
| </head> |
| <body> |
| <div id="top"><!-- do not remove this div, it is closed by doxygen! --> |
| <div id="titlearea" style="height: 110px;"> |
| <table cellspacing="0" cellpadding="0"> |
| <tbody> |
| <tr style="height: 56px;"> |
| <td id="commonprojectlogo"> |
| <img alt="Logo" src="fpl_logo_small.png"/> |
| </td> |
| <td style="padding-left: 0.5em;"> |
| <div id="projectname">FlatBuffers |
| </div> |
| <div style="font-size:12px;"> |
| An open source project by <a href="https://developers.google.com/games/#Tools">FPL</a>. |
| </div> |
| </td> |
| </tr> |
| </tbody> |
| </table> |
| </div> |
| <!-- end header part --> |
| <!-- Generated by Doxygen 1.9.1 --> |
| <script type="text/javascript"> |
| /* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&dn=gpl-2.0.txt GPL-v2 */ |
| var searchBox = new SearchBox("searchBox", "search",false,'Search','.html'); |
| /* @license-end */ |
| </script> |
| <script type="text/javascript" src="menudata.js"></script> |
| <script type="text/javascript" src="menu.js"></script> |
| <script type="text/javascript"> |
| /* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&dn=gpl-2.0.txt GPL-v2 */ |
| $(function() { |
| initMenu('',true,false,'search.php','Search'); |
| $(document).ready(function() { init_search(); }); |
| }); |
| /* @license-end */</script> |
| <div id="main-nav"></div> |
| </div><!-- top --> |
| <div id="side-nav" class="ui-resizable side-nav-resizable"> |
| <div id="nav-tree"> |
| <div id="nav-tree-contents"> |
| <div id="nav-sync" class="sync"></div> |
| </div> |
| </div> |
| <div id="splitbar" style="-moz-user-select:none;" |
| class="ui-resizable-handle"> |
| </div> |
| </div> |
| <script type="text/javascript"> |
| /* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&dn=gpl-2.0.txt GPL-v2 */ |
| $(document).ready(function(){initNavTree('flatbuffers_guide_use_c-sharp.html',''); initResizable(); }); |
| /* @license-end */ |
| </script> |
| <div id="doc-content"> |
| <!-- window showing the filter options --> |
| <div id="MSearchSelectWindow" |
| onmouseover="return searchBox.OnSearchSelectShow()" |
| onmouseout="return searchBox.OnSearchSelectHide()" |
| onkeydown="return searchBox.OnSearchSelectKey(event)"> |
| </div> |
| |
| <!-- iframe showing the search results (closed by default) --> |
| <div id="MSearchResultsWindow"> |
| <iframe src="javascript:void(0)" frameborder="0" |
| name="MSearchResults" id="MSearchResults"> |
| </iframe> |
| </div> |
| |
| <div class="PageDoc"><div class="header"> |
| <div class="headertitle"> |
| <div class="title">Use in C# </div> </div> |
| </div><!--header--> |
| <div class="contents"> |
| <div class="textblock"><p><a class="anchor" id="md_CsharpUsage"></a></p> |
| <h1><a class="anchor" id="autotoc_md88"></a> |
| Before you get started</h1> |
| <p>Before diving into the FlatBuffers usage in C#, it should be noted that the <a class="el" href="flatbuffers_guide_tutorial.html">Tutorial</a> page has a complete guide to general FlatBuffers usage in all of the supported languages (including C#). This page is designed to cover the nuances of FlatBuffers usage, specific to C#.</p> |
| <p>You should also have read the <a class="el" href="flatbuffers_guide_building.html">Building</a> documentation to build <code>flatc</code> and should be familiar with <a class="el" href="flatbuffers_guide_using_schema_compiler.html">Using the schema compiler</a> and <a class="el" href="flatbuffers_guide_writing_schema.html">Writing a schema</a>.</p> |
| <h1><a class="anchor" id="autotoc_md89"></a> |
| FlatBuffers C# code location</h1> |
| <p>The code for the FlatBuffers C# library can be found at <code>flatbuffers/net/FlatBuffers</code>. You can browse the library on the <a href="https://github.com/google/flatbuffers/tree/master/net/ |
| FlatBuffers">FlatBuffers GitHub page</a>.</p> |
| <h1><a class="anchor" id="autotoc_md90"></a> |
| Building the FlatBuffers C# library</h1> |
| <p>The <code>FlatBuffers.csproj</code> project contains multitargeting for .NET Standard 2.1, .NET Standard 2.0, and .NET Framework 4.6 (Unity 2017). Support for .NET Framework 3.5 (Unity 5) is provided by the <code>FlatBuffers.net35.csproj</code> project. In most cases (including Unity 2018 and newer), .NET Standard 2.0 is recommended.</p> |
| <p>You can build for a specific framework target when using the cross-platform <a href="https://dotnet.microsoft.com/download">.NET Core SDK</a> by adding the <code>-f</code> command line option:</p> |
| <div class="fragment"><div class="line">dotnet build -f netstandard2.0 "FlatBuffers.csproj"</div> |
| </div><!-- fragment --><p>The <code>FlatBuffers.csproj</code> project also provides support for defining various conditional compilation symbols (see "Conditional compilation symbols" section below) using the <code>-p</code> command line option:</p> |
| <div class="fragment"><div class="line">dotnet build -f netstandard2.1 -p:ENABLE_SPAN_T=true -p:UNSAFE_BYTEBUFFER=true "FlatBuffers.csproj"</div> |
| </div><!-- fragment --><h1><a class="anchor" id="autotoc_md91"></a> |
| Testing the FlatBuffers C# library</h1> |
| <p>The code to test the libraries can be found at <code>flatbuffers/tests</code>.</p> |
| <p>The test code for C# is located in the <a href="https://github.com/ |
| google/flatbuffers/tree/master/tests/FlatBuffers.Test">FlatBuffers.Test</a> subfolder. To run the tests, open <code>FlatBuffers.Test.csproj</code> in <a href="https://www.visualstudio.com">Visual Studio</a>, and compile/run the project.</p> |
| <p>Optionally, you can run this using <a href="http://www.mono-project.com/">Mono</a> instead. Once you have installed Mono, you can run the tests from the command line by running the following commands from inside the <code>FlatBuffers.Test</code> folder:</p> |
| <div class="fragment"><div class="line">mcs *.cs ../MyGame/Example/*.cs ../../net/FlatBuffers/*.cs</div> |
| <div class="line">mono Assert.exe</div> |
| </div><!-- fragment --><h1><a class="anchor" id="autotoc_md92"></a> |
| Using the FlatBuffers C# library</h1> |
| <p><em>Note: See <a class="el" href="flatbuffers_guide_tutorial.html">Tutorial</a> for a more in-depth example of how to use FlatBuffers in C#.</em></p> |
| <p>FlatBuffers supports reading and writing binary FlatBuffers in C#.</p> |
| <p>To use FlatBuffers in your own code, first generate C# classes from your schema with the <code>--csharp</code> option to <code>flatc</code>. Then you can include both FlatBuffers and the generated code to read or write a FlatBuffer.</p> |
| <p>For example, here is how you would read a FlatBuffer binary file in C#: First, import the library and generated code. Then, you read a FlatBuffer binary file into a <code>byte[]</code>. You then turn the <code>byte[]</code> into a <code>ByteBuffer</code>, which you pass to the <code>GetRootAsMyRootType</code> function:</p> |
| <div class="fragment"><div class="line"><span class="keyword">using</span> MyGame.Example;</div> |
| <div class="line"><span class="keyword">using</span> <a class="code" href="namespace_flat_buffers.html">FlatBuffers</a>;</div> |
| <div class="line"> </div> |
| <div class="line"><span class="comment">// This snippet ignores exceptions for brevity.</span></div> |
| <div class="line"><span class="keywordtype">byte</span>[] data = File.ReadAllBytes(<span class="stringliteral">"monsterdata_test.mon"</span>);</div> |
| <div class="line"> </div> |
| <div class="line">ByteBuffer bb = <span class="keyword">new</span> ByteBuffer(data);</div> |
| <div class="line">Monster monster = Monster.GetRootAsMonster(bb);</div> |
| <div class="ttc" id="anamespace_flat_buffers_html"><div class="ttname"><a href="namespace_flat_buffers.html">FlatBuffers</a></div><div class="ttdef"><b>Definition:</b> FlatBufferBuilder.cs:27</div></div> |
| </div><!-- fragment --><p>Now you can access the data from the <code>Monster monster</code>:</p> |
| <div class="fragment"><div class="line"><span class="keywordtype">short</span> hp = monster.Hp;</div> |
| <div class="line">Vec3 pos = monster.Pos;</div> |
| </div><!-- fragment --><p>C# code naming follows standard C# style with PascalCasing identifiers, e.g. <code>GetRootAsMyRootType</code>. Also, values (except vectors and unions) are available as properties instead of parameterless accessor methods. The performance-enhancing methods to which you can pass an already created object are prefixed with <code>Get</code>, e.g.:</p> |
| <div class="fragment"><div class="line"><span class="comment">// property</span></div> |
| <div class="line">var pos = monster.Pos;</div> |
| <div class="line"> </div> |
| <div class="line"><span class="comment">// method filling a preconstructed object</span></div> |
| <div class="line">var preconstructedPos = <span class="keyword">new</span> Vec3();</div> |
| <div class="line">monster.GetPos(preconstructedPos);</div> |
| </div><!-- fragment --><h1><a class="anchor" id="autotoc_md93"></a> |
| Storing dictionaries in a FlatBuffer</h1> |
| <p>FlatBuffers doesn't support dictionaries natively, but there is support to emulate their behavior with vectors and binary search, which means you can have fast lookups directly from a FlatBuffer without having to unpack your data into a <code>Dictionary</code> or similar.</p> |
| <p>To use it:</p><ul> |
| <li>Designate one of the fields in a table as the "key" field. You do this by setting the <code>key</code> attribute on this field, e.g. <code>name:string (key)</code>. You may only have one key field, and it must be of string or scalar type.</li> |
| <li>Write out tables of this type as usual, collect their offsets in an array.</li> |
| <li>Instead of calling standard generated method, e.g.: <code>Monster.createTestarrayoftablesVector</code>, call <code>CreateSortedVectorOfMonster</code> in C# which will first sort all offsets such that the tables they refer to are sorted by the key field, then serialize it.</li> |
| <li>Now when you're accessing the FlatBuffer, you can use the <code>ByKey</code> accessor to access elements of the vector, e.g.: <code>monster.TestarrayoftablesByKey("Frodo")</code> in C#, which returns an object of the corresponding table type, or <code>null</code> if not found. <code>ByKey</code> performs a binary search, so should have a similar speed to <code>Dictionary</code>, though may be faster because of better caching. <code>ByKey</code> only works if the vector has been sorted, it will likely not find elements if it hasn't been sorted.</li> |
| </ul> |
| <h1><a class="anchor" id="autotoc_md94"></a> |
| Text parsing</h1> |
| <p>There currently is no support for parsing text (Schema's and JSON) directly from C#, though you could use the C++ parser through native call interfaces available to each language. Please see the C++ documentation for more on text parsing.</p> |
| <h1><a class="anchor" id="autotoc_md95"></a> |
| Object based API</h1> |
| <p>FlatBuffers is all about memory efficiency, which is why its base API is written around using as little as possible of it. This does make the API clumsier (requiring pre-order construction of all data, and making mutation harder).</p> |
| <p>For times when efficiency is less important a more convenient object based API can be used (through <code>--gen-object-api</code>) that is able to unpack & pack a FlatBuffer into objects and standard <code>System.Collections.Generic</code> containers, allowing for convenient construction, access and mutation.</p> |
| <p>To use:</p> |
| <div class="fragment"><div class="line"><span class="comment">// Deserialize from buffer into object.</span></div> |
| <div class="line">MonsterT monsterobj = GetMonster(flatbuffer).UnPack();</div> |
| <div class="line"> </div> |
| <div class="line"><span class="comment">// Update object directly like a C# class instance.</span></div> |
| <div class="line">Console.WriteLine(monsterobj.Name);</div> |
| <div class="line">monsterobj.Name = <span class="stringliteral">"Bob"</span>; <span class="comment">// Change the name.</span></div> |
| <div class="line"> </div> |
| <div class="line"><span class="comment">// Serialize into new flatbuffer.</span></div> |
| <div class="line">FlatBufferBuilder fbb = <span class="keyword">new</span> FlatBufferBuilder(1);</div> |
| <div class="line">fbb.Finish(Monster.Pack(fbb, monsterobj).Value);</div> |
| </div><!-- fragment --><h2><a class="anchor" id="autotoc_md96"></a> |
| Json Serialization</h2> |
| <p>An additional feature of the object API is the ability to allow you to serialize & deserialize a JSON text. To use Json Serialization, add <code>--cs-gen-json-serializer</code> option to <code>flatc</code> and add <code>Newtonsoft.Json</code> nuget package to csproj.</p> |
| <div class="fragment"><div class="line"><span class="comment">// Deserialize MonsterT from json</span></div> |
| <div class="line"><span class="keywordtype">string</span> jsonText = File.ReadAllText(<span class="stringliteral">@"Resources/monsterdata_test.json"</span>);</div> |
| <div class="line">MonsterT mon = MonsterT.DeserializeFromJson(jsonText);</div> |
| <div class="line"> </div> |
| <div class="line"><span class="comment">// Serialize MonsterT to json</span></div> |
| <div class="line"><span class="keywordtype">string</span> jsonText2 = mon.SerializeToJson();</div> |
| </div><!-- fragment --><ul> |
| <li>Limitation<ul> |
| <li><code>hash</code> attribute currentry not supported.</li> |
| </ul> |
| </li> |
| <li>NuGet package Dependency<ul> |
| <li><a href="https://github.com/JamesNK/Newtonsoft.Json">Newtonsoft.Json</a></li> |
| </ul> |
| </li> |
| </ul> |
| <h1><a class="anchor" id="autotoc_md97"></a> |
| Conditional compilation symbols</h1> |
| <p>There are three conditional compilation symbols that have an impact on performance/features of the C# <code>ByteBuffer</code> implementation.</p> |
| <ul> |
| <li><p class="startli"><code>UNSAFE_BYTEBUFFER</code></p> |
| <p class="startli">This will use unsafe code to manipulate the underlying byte array. This can yield a reasonable performance increase.</p> |
| </li> |
| <li><p class="startli"><code>BYTEBUFFER_NO_BOUNDS_CHECK</code></p> |
| <p class="startli">This will disable the bounds check asserts to the byte array. This can yield a small performance gain in normal code.</p> |
| </li> |
| <li><p class="startli"><code>ENABLE_SPAN_T</code></p> |
| <p class="startli">This will enable reading and writing blocks of memory with a <code>Span<T></code> instead of just <code>T[]</code>. You can also enable writing directly to shared memory or other types of memory by providing a custom implementation of <code>ByteBufferAllocator</code>. <code>ENABLE_SPAN_T</code> also requires <code>UNSAFE_BYTEBUFFER</code> to be defined, or .NET Standard 2.1.</p> |
| </li> |
| </ul> |
| <p>Using <code>UNSAFE_BYTEBUFFER</code> and <code>BYTEBUFFER_NO_BOUNDS_CHECK</code> together can yield a performance gain of ~15% for some operations, however doing so is potentially dangerous. Do so at your own risk!</p> |
| <p><br /> |
| </p> |
| </div></div><!-- contents --> |
| </div><!-- PageDoc --> |
| </div><!-- doc-content --> |
| <!-- Google Analytics --> |
| <script> |
| (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ |
| (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), |
| m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) |
| })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); |
| ga('create', 'UA-49880327-7', 'auto'); |
| ga('send', 'pageview'); |
| </script> |
| </body> |
| </html> |