我想设置一个带有字节值的flatbuffers表字段。
到目前为止,我所成功完成的工作如下:
namespace sint.bl;
table Response {
id:short;
body:[byte];
}
import flatbuffers
import pickle
import sint.bl.Request
import sint.bl.Response
my_dict = {
'a': 1
}
my_bytes = pickle.dumps(my_dict)
builder = flatbuffers.Builder(1024)
sint.bl.Response.ResponseStart(builder)
sint.bl.Response.ResponseAddId(builder, 100)
# this line throws the exception:
# ValueError: invalid literal for int()
# with base 10: b'\x80\x03}q\x00X\x01\x00\x00\x00aq\x01K\x01s.'
sint.bl.Response.ResponseAddBody(builder, my_bytes)
response = sint.bl.Response.ResponseEnd(builder)
builder.Finish(response)
response_pdu = builder.Output()
使用平面缓冲区管理字节编码字段的正确方法是什么?
答案 0 :(得分:1)
ResponseAddBody
的参数是序列化字节向量的偏移量(错误中的int
),而不是直接的bytes
对象。需要在表的之前进行序列化。
因此,在创建builder
之后,立即调用builder.CreateByteVector(my_bytes)
,然后将其结果传递给ResponseAddBody
。
或者,以下是手动创建任何矢量的方法(选择Python,搜索inventory
):https://google.github.io/flatbuffers/flatbuffers_guide_tutorial.html
注意,您似乎正在使用2个序列化系统,pickle和FlatBuffers。您最好使用例如在FlatBuffers中直接编码选择的数据。 table Foo { a:int }
代替您的字典,或者如果它必须是开放式字典,则为table KeyValue { key:string; value:int; }
或类似的向量。还是联合,取决于您的用例。