如何使用字节数组设置 flatbuffers table 字段

How to set a flatbuffers table field with bytes array

我想设置一个带有字节值的 flatbuffers table 字段。

我目前管理的,没有成功,就是下面的。

平面缓冲区架构:

namespace sint.bl;

table Response {
    id:short;
    body:[byte];
}

python示例代码:

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()

使用平面缓冲区管理字节编码字段的正确方法是什么?

ResponseAddBody 的参数是序列化字节向量(错误中的 int)的偏移量,而不是直接的 bytes 对象。这需要在 before table.

序列化

因此,在创建 builder 之后,立即调用 builder.CreateByteVector(my_bytes),稍后将其结果传递给 ResponseAddBody

或者,以下是手动创建任何矢量的方法(select 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; } 或类似的向量。或联合,具体取决于您的用例。