【问题标题】:How to set a flatbuffers table field with bytes array如何使用字节数组设置 flatbuffers 表字段
【发布时间】:2019-10-18 10:24:57
【问题描述】:

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

到目前为止我所管理的,没有成功,是以下。

平面缓冲区架构:

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

使用 flatbuffers 管理字节编码字段的正确方法是什么?

【问题讨论】:

    标签: python flatbuffers


    【解决方案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; } 或类似的向量。或联合,具体取决于您的用例。

    【讨论】:

    • 感谢您的解释。在解码方面是否有一种方法可以取回整个字节数组?我发现的唯一示例是像monster.Inventory(2) 这样的索引访问。
    • InventoryAsNumpy 但似乎不适用于常规字节数组。在 github 上打开一个问题,或者更好的是,一个 PR。
    猜你喜欢
    • 1970-01-01
    • 2020-11-10
    • 1970-01-01
    • 1970-01-01
    • 2012-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多