FlatBuffers 是一个序列化开源库,实现了与 Protocol Buffers,Thrift,Apache Avro,SBE 和 Cap’n Proto 类似的序列化格式,
主要由 Wouter van Oortmerssen 编写,并由 Google 开源。Oortmerssen 最初为 Android 游戏和注重性能的应用而开发了FlatBuffers。
现在它具有C ++,C#,C,Go,Java,PHP,Python 和 JavaScript 的端口。
[https://github.com/google/flatbuffers.git]
https://github.com/google/flatbuffers/releases
这里有编译好的版本,下载对应文件解压即可使用
先创建自己的schema文件
namespace parameters;
table ParameterData
{
name:string;
size:int;
data:[float];
}
table Parameters
{
name:string;
data:[ParameterData];
}
root_type Parameters;
flatc --python --gen-object-api ./schema.fbs
执行完以上命令会生成一个描述文件,定义好了上述两个Table的实现
from parameters import Parameters, ParameterData
builder = flatbuffers.Builder(0)
param1 = builder.CreateString('emb_weight')
weight=np.array([1.0, 2.0, 3.0, 4.0, 5.0], np.float32)
bytesweight = weight.tobytes()
float_w = np.frombuffer(bytesweight, dtype=weight.dtype)
ParameterData.ParameterDataStartDataVector(builder, len(bytesweight))
#We need to seek the header to correct place before writing into Bytes array.
builder.head = builder.head - len(bytesweight)
builder.Bytes[builder.head : (builder.head + len(bytesweight))] = bytesweight
data = builder.EndVector()
ParameterData.ParameterDataStart(builder)
ParameterData.ParameterDataAddName(builder, param1)
ParameterData.ParameterDataAddSize(builder, 5)
ParameterData.ParameterDataAddData(builder, data)
allparameter = ParameterData.ParameterDataEnd(builder)
Parameters.ParametersStartDataVector(builder, 1)
builder.PrependUOffsetTRelative(allparameter)
params = builder.EndVector()
domain_name = builder.CreateString("domain")
Parameters.ParametersStart(builder)
Parameters.ParametersAddName(builder, domain_name)
Parameters.ParametersAddData(builder, params)
all_params = Parameters.ParametersEnd(builder)
builder.Finish(all_params)
buf = builder.Output()
with open("parameters.bin", mode="wb") as f:
f.write(buf)```
rbuf = open('parameters.bin', 'rb').read()
rbuf = bytearray(rbuf)
resparam = Parameters.Parameters.GetRootAsParameters(rbuf, 0)
print("resparam--", resparam.Name())
print("resparam-data-name-", resparam.Data(0).Name())
print("resparam-data-size-", resparam.Data(0).Size())
print("resparam-data-length-", resparam.Data(0).DataLength())
for i in range(resparam.Data(0).Size()):
print("resparam-data--", i, resparam.Data(0).Data(i))
代码输出结果如下:
resparam-data-name- b'emb_weight'
resparam-data-size- 5
resparam-data-length- 20
resparam-data-- 0 1.0
resparam-data-- 1 2.0
resparam-data-- 2 3.0
resparam-data-- 3 4.0
resparam-data-- 4 5.0