Flatbufer 基础

1. Flatbuffer 概要:

在这里插入图片描述

2. Flatbuffer 安装:

$ choice "folder for installation"
$ cd "folder for installation"
$ git clone https://github.com/google/flatbuffers.git
$ cd flatbuffers
$ cmake -G "Unix Makefiles" (install cmake if need)
$ make && sudo make install

3. Flatbuffer write schema/jsonfile

3.1 schema(左) vs json(右)

在这里插入图片描述

3.2 手写schema 以及 jsonfile

// example IDL file, mygame.fbs

namespace MyGame;

attribute "priority";

enum Color : byte { Red = 1, Green, Blue }

union Any { Monster }

struct Vec3 {
  x:float;
  y:float;
  z:float;
}

table Monster {
  pos:Vec3;
  mana:short = 150;
  hp:short = 100;
  name:string;
  friendly:bool = false (deprecated, priority: 1);
  inventory:[ubyte];
  color:Color = Blue;
  test:Any;
}

root_type Monster;

{
    "pos": {
    	"x": "1.0",
    	"y": "2.0",
    	"z": "3.0"
    },
    "mana": "200",
    "name": "jianlei",
    "inventory" :
    [
    	"1",
    	"2",
    	"3"
    ],
    "color": "Green"
}

4. Flatbuffer fbs/json compile

4.1 fbs comile

flatc -c mygame.fbs
# comments
# output: mygame_generated.h

4.2 json compile

flatc -b mygame.fbs mygame.json

4.3 app.cpp usage

/*app.cpp*/
	#include "flatbuffers/flatbuffers.h"
	#include "mygame_generated.h"
	#include <iostream> // C++ header file for printing
	#include <fstream> // C++ header file for file access
	 
	 
	std::ifstream infile;
	infile.open("mygame.bin", std::ios::binary | std::ios::in);
	infile.seekg(0,std::ios::end);
	int length = infile.tellg();
	infile.seekg(0,std::ios::beg);
	char *data = new char[length];
	infile.read(data, length);
	infile.close();
	 
	auto monster = GetMonster(data);
	std::cout << "hp : " << monster->hp() << std::endl;            // `80`
	std::cout << "mana : " << monster->mana() << std::endl;        // default value of `150`
	std::cout << "name : " << monster->name()->c_str() << std::endl;        // "MyMonster"
	
	return 0;
}

5. Flatbuffer 资料:

5.1 install flatbuffer

5.2 flatbuffer guide

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值