FlatBuffer入门笔记
FlatBuffer入门笔记
1 flatbuffer资料
flatbuffer下载地址:https://github.com/google/flatbuffers
flatbuffer官方使用文档:https://google.github.io/flatbuffers/index.html#flatbuffers_overview
flatbuffer官方测试用例:https://google.github.io/flatbuffers/flatbuffers_guide_use_cpp.html
2 编写IDL|Schema
2.1 IDL测试文件
引用官方测试使用的IDL
// Example IDL file for our monster's schema.
namespace MyGame.Sample;
enum Color:byte { Red = , Green, Blue = }
union Equipment { Weapon } // Optionally add more tables.
struct Vec3 {
x:float;
y:float;
z:float;
}
table Monster {
pos:Vec3; // Struct.
mana:short = ;
hp:short = ;
name:string;
friendly:bool = false (deprecated);
inventory:[ubyte]; // Vector of scalars.
color:Color = Blue; // Enum.
weapons:[Weapon]; // Vector of tables.
equipped:Equipment; // Union.
path:[Vec3]; // Vector of structs.
}
table Weapon {
name:string;
damage:short;
}
root_type Monster;
2.2 生成桩文件
利用flatc.exe生成IDL对应的桩代码,命令格式为
flatc [ GENERATOR OPTIONS ] [ -o PATH ] [ -I PATH ] [ -S ] FILES... [ -- FILES...]
flatc --cpp monster.fbs
flatbuffer使用模板编程,仅生成h文件。对应的文件名为filename_generated.h。这里生成monster_generated.h文件。
2.3 IDL数据类型
2.3.1 Table
Table是FlatBuffer定义的主要数据类型,一个Table包含一个名称(如2.1的Monster),以及一组字段(如2.1的Monster)。每个字段由名称、类型及默认值组成。
FlatBuffer每个字段都是可选的,这由FlatBUffer的线性实现机制决定:空闲字段仅填充默认占位值,而不占用分配size。
2.3.2 Struct
Struct只包含数值类型与其他struct,与Table相比,Struct使用更少的存储空间以及更快的访问速度。
2.3.3 Type
内建的数值类型有:
- 8 bit: byte (int8), ubyte (uint8), bool
- 16 bit: short (int16), ushort (uint16)
- 32 bit: int (int32), uint (uint32), float (float32)
- 64 bit: long (int64), ulong (uint64), double (float64)
内建的非数值类型有:
- vector,用[]表示
- string
- 指向其他Table、struct、enum、unions的引用
2.3.4 Enums
定义了一系列的命名常量,可以给定默认值。第一个变量的默认值为0。
2.3.5 Namespaces
可以定义嵌套的namespace,用.分割。
2.3.6 Root type
定义序列化的root table或者struct。
3 序列化与反序列化
对2.1例子的序列化和反序列化过程实现在sample_binary.cpp。
3.1 序列化
// Build up a serialized buffer algorithmically:
flatbuffers::FlatBufferBuilder builder; //申请一个flatbuffer // First, lets serialize some weapons for the Monster: A 'sword' and an 'axe'.
auto weapon_one_name = builder.CreateString("Sword"); //在buffer中申请string
short weapon_one_damage = ; auto weapon_two_name = builder.CreateString("Axe"); //在buffer中申请string
short weapon_two_damage = ; // Use the `CreateWeapon` shortcut to create Weapons with all fields set.
auto sword = CreateWeapon(builder, weapon_one_name, weapon_one_damage); //桩代码中实现
auto axe = CreateWeapon(builder, weapon_two_name, weapon_two_damage); // // Create a FlatBuffer's `vector` from the `std::vector`.
std::vector<flatbuffers::Offset<Weapon>> weapons_vector;
weapons_vector.push_back(sword);
weapons_vector.push_back(axe);
auto weapons = builder.CreateVector(weapons_vector); //在buffer中序列化vector // Second, serialize the rest of the objects needed by the Monster.
auto position = Vec3(1.0f, 2.0f, 3.0f); auto name = builder.CreateString("MyMonster"); unsigned char inv_data[] = { , , , , , , , , , };
auto inventory = builder.CreateVector(inv_data, ); // Shortcut for creating monster with all fields set:
auto orc = CreateMonster(builder, &position, , , name, inventory,
Color_Red, weapons, Equipment_Weapon, axe.Union()); builder.Finish(orc); // Serialize the root of the object. //序列化对象root // We now have a FlatBuffer we can store on disk or send over a network. // ** file/network code goes here :) **
3.2 反序列化
// access builder.GetBufferPointer() for builder.GetSize() bytes // Instead, we're going to access it right away (as if we just received it). // Get access to the root:
auto monster = GetMonster(builder.GetBufferPointer()); //获取根对象指针 // Get and test some scalar types from the FlatBuffer.
assert(monster->hp() == );
assert(monster->mana() == ); // default
assert(monster->name()->str() == "MyMonster"); // Get and test a field of the FlatBuffer's `struct`.
auto pos = monster->pos();
assert(pos);
assert(pos->z() == 3.0f);
(void)pos; // Get a test an element from the `inventory` FlatBuffer's `vector`.
auto inv = monster->inventory();
assert(inv);
assert(inv->Get() == );
(void)inv; // Get and test the `weapons` FlatBuffers's `vector`.
std::string expected_weapon_names[] = { "Sword", "Axe" };
short expected_weapon_damages[] = { , };
auto weps = monster->weapons();
for (unsigned int i = ; i < weps->size(); i++) {
assert(weps->Get(i)->name()->str() == expected_weapon_names[i]);
assert(weps->Get(i)->damage() == expected_weapon_damages[i]);
}
(void)expected_weapon_names;
(void)expected_weapon_damages; // Get and test the `Equipment` union (`equipped` field).
assert(monster->equipped_type() == Equipment_Weapon);
auto equipped = static_cast<const Weapon *>(monster->equipped());
assert(equipped->name()->str() == "Axe");
assert(equipped->damage() == );
(void)equipped;
4 FlatBuffer原理?网上找的一些文档
https://www.jianshu.com/p/fa999434776a

FlatBuffer入门笔记的更多相关文章
- 每天成长一点---WEB前端学习入门笔记
WEB前端学习入门笔记 从今天开始,本人就要学习WEB前端了. 经过老师的建议,说到他每天都会记录下来新的知识点,每天都是在围绕着这些问题来度过,很有必要每天抽出半个小时来写一个知识总结,及时对一天工 ...
- ES6入门笔记
ES6入门笔记 02 Let&Const.md 增加了块级作用域. 常量 避免了变量提升 03 变量的解构赋值.md var [a, b, c] = [1, 2, 3]; var [[a,d] ...
- [Java入门笔记] 面向对象编程基础(二):方法详解
什么是方法? 简介 在上一篇的blog中,我们知道了方法是类中的一个组成部分,是类或对象的行为特征的抽象. 无论是从语法和功能上来看,方法都有点类似与函数.但是,方法与传统的函数还是有着不同之处: 在 ...
- React.js入门笔记
# React.js入门笔记 核心提示 这是本人学习react.js的第一篇入门笔记,估计也会是该系列涵盖内容最多的笔记,主要内容来自英文官方文档的快速上手部分和阮一峰博客教程.当然,还有我自己尝试的 ...
- redis入门笔记(2)
redis入门笔记(2) 上篇文章介绍了redis的基本情况和支持的数据类型,本篇文章将介绍redis持久化.主从复制.简单的事务支持及发布订阅功能. 持久化 •redis是一个支持持久化的内存数据库 ...
- redis入门笔记(1)
redis入门笔记(1) 1. Redis 简介 •Redis是一款开源的.高性能的键-值存储(key-value store).它常被称作是一款数据结构服务器(data structure serv ...
- OpenGLES入门笔记四
原文参考地址:http://www.cnblogs.com/zilongshanren/archive/2011/08/08/2131019.html 一.编译Vertex Shaders和Fragm ...
- OpenGLES入门笔记三
在入门笔记一中比较详细的介绍了顶点着色器和片面着色器. 在入门笔记二中讲解了简单的创建OpenGL场景流程的实现,但是如果在场景中渲染任何一种几何图形,还是需要入门笔记一中的知识:Vertex Sha ...
- unity入门笔记
我于2010年4月1日硕士毕业加入完美时空, 至今5年整.刚刚从一家公司的微端(就是端游技术+页游思想, 具体点就是c++开发, directX渲染, 资源采取所需才会下载)项目的前端主程职位离职, ...
随机推荐
- nodejs与c语言交互应用实例
nodejs与c/c++交互目前主流的方式有两种,node addon c++ 和 node-ffi . 1.node addon c++ 1)nodejs从c语言读取数据 addon.c #incl ...
- TensorFlow学习笔记(三)-- feed_dict 使用
个人理解:就是TF的一种输入语法. 跟C语言的scanf(),C++的 cin>> 意思差不多,只是长相奇怪了点而已. 做完下面几个例子,基本也就适应了. 首先占位符申请空间:使用的时候, ...
- JAVA math包
Math类: java.lang.Math 类中包含基本的数字操作,如指数.对数.平方根和三角函数. java.math是一个包,提供用于执行任意精度整数(BigInteger)算法和任意精度小数(B ...
- Spring整合jdbc编程
一.Spring对Jdbc的支持 Spring为了提供对Jdbc的支持,在Jdbc API的基础上封装了一套实现,以此建立一个 JDBC 存取框架. 作为 Spring JDBC 框架的核心, ...
- matplotlib 的 subplot, axes and axis
fig = plt.figure('多图', (10, 10), dpi=80) #第一个指定窗口名称,第二个指定图片大小,创建一个figure对象 plt.subplot(222) #2*2的第二个 ...
- SQL Server 使用 Hierarchyid 操作层次结构数据
层次结构数据定义为一组通过层次结构关系互相关联的数据项. 在层次结构关系中,一个数据项是另一个项的父级或子级. sql server2008开始内置的 hierarchyid 数据类型使存储和查询层次 ...
- 『NiFi 学习之路』自定义 —— 组件的自定义及使用
一.概述 许多业务仅仅使用官方提供的组件不能够满足性能上的需求,往往要通过高度可定制的组件来完成特定的业务需求. 而 NiFi 提供了自定义组件的这种方式. 二.自定义 Processor 占坑待续 ...
- ZOJ - 4048 Red Black Tree (LCA+贪心) The 2018 ACM-ICPC Asia Qingdao Regional Contest, Online
题意:一棵树上有m个红色结点,树的边有权值.q次查询,每次给出k个点,每次查询有且只有一次机会将n个点中任意一个点染红,令k个点中距离红色祖先距离最大的那个点的距离最小化.q次查询相互独立. 分析:数 ...
- POJ 3905 Perfect Election (2-SAT 判断可行)
题意:有N个人参加选举,有M个条件,每个条件给出:i和j竞选与否会只要满足二者中的一项即可.问有没有方案使M个条件都满足. 分析:读懂题目即可发现是2-SAT的问题.因为只要每个条件中满足2个中的一个 ...
- 【转】深入浅出UML类图
转自:http://www.cppblog.com/API/archive/2013/07/04/201506.html 在UML 2.0的13种图形中,类图是使用频率最高的UML图之一.Martin ...