Python 如何使用字节数组设置flatbuffers表字段
我想用字节值设置一个flatbuffers表字段 到目前为止,我成功地做到了以下几点 flatbuffers架构: python示例代码:Python 如何使用字节数组设置flatbuffers表字段,python,flatbuffers,Python,Flatbuffers,我想用字节值设置一个flatbuffers表字段 到目前为止,我成功地做到了以下几点 flatbuffers架构: python示例代码: 使用flatbuffers管理字节编码字段的正确方法是什么?ResponseAddBody的参数是序列化字节向量的偏移量(错误中的int),而不是直接使用字节对象。这需要在表之前序列化 因此,在创建builder之后,立即调用builder.CreateByteVector(my_bytes),稍后将结果传递给ResponseAddBody 或者,这里介绍了
使用flatbuffers管理字节编码字段的正确方法是什么?ResponseAddBody的参数是序列化字节向量的偏移量(错误中的
int
),而不是直接使用字节
对象。这需要在表之前序列化
因此,在创建builder
之后,立即调用builder.CreateByteVector(my_bytes)
,稍后将结果传递给ResponseAddBody
或者,这里介绍了如何手动创建任何向量(选择Python,搜索清单
):
注意,您似乎使用了两个序列化系统:pickle和flatbuffer。最好直接在FlatBuffers中对拾取的数据进行编码,例如使用
表Foo{a:int}
而不是dict,或者如果它必须是一个开放式dict,则使用表KeyValue{key:string;value:int;}
或类似的向量。或联合,具体取决于您的使用案例。谢谢您的解释。在解码方面,有没有一种方法可以取回整个字节数组?我发现的唯一一个例子是像monster.Inventory(2)
这样的索引访问。有InventoryAsNumpy
,但似乎不适用于常规字节数组。在github上打开一个问题,或者更好,打开一个PR。
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()