使用平面缓冲区编写结构向量

Writing a vector of struct with flatbuffers

我有以下 类:

命名空间消息;

struct BBox {
 xmin:float;
 xmax:float;
 ymin:float;
 ymax:float;
}

table msg {
  key:string;
  boxes: [BBox];
}

root_type Message;

为了创建对象,我做了一些事情

b = flatbuffers.Builder(0)
msg.msgStart(b)
msg.msgAddKey(b, b.CreateString(key))

v = flatbuffers.Builder(0)
size = len(boxes)
msg.msgBoxesVector(v, size)
for elem in boxes:
    xmin, ymin, xmax, ymax = elem
    BBox.CreateBBox(v, xmin, xmax, ymin, ymax)
boxes = v.EndVector(size)
msg.msgAddBoxes(b, boxes)
obj = msg.msgEnd(b)
b.Finish(obj)

并且没有抛出任何错误

但是当我尝试显示结果时,键是好的但是向量的大小和内容是错误的

rep = msg.msg.GetRootAsmsg(bytearray(b.Output()), 0)
print rep.BoxesLength()  # give me 4 instead of 1 
for i in range(rep.BoxesLength()):
    print rep.Boxes(i).Xmin(),  rep.Boxes(i).Ymin()
    print rep.Boxes(i).Xmax(),  rep.Boxes(i).Ymax()

我们有一个关于 Python 端口没有做足够的错误检查的未决问题:https://github.com/google/flatbuffers/issues/299

字符串和向量的创建应该发生在 msgStart 之前。另外,您应该只使用一个 Builder 对象(只使用 b,而不是 v),因为上面的代码从一个缓冲区引用到另一个缓冲区,这是行不通的。

编辑:当您尝试嵌套 vector/string/table 代时,Python 实现现在可以正确地发出错误信号。但是它仍然无法检测到跨缓冲区偏移量。

我会给出我所做的,希望它可以帮助其他人(基于 Aardappel 回答)

b = flatbuffers.Builder(0)

if boxes:
    boxesOffsets = 0
    msg.msgStartBoxesVector(b, len(boxes))
    for elem in boxes:
        xmin, ymin, xmax, ymax = elem
        BBox.CreateBBox(b, float(xmin), float(xmax), float(ymin), float(ymax))
    boxesOffsets = b.EndVector(len(boxes))

msg.msgStart(b)
msg.msgAddKey(b, b.CreateString(key))
msg.msgAddUrl(b, b.CreateString(url))
msg.msgAddCountry(b, b.CreateString(country))
msg.msgAddLimit(b, limit)

if boxes:
    msg.msgAddBoxes(b, boxesOffsets)

obj = msg.msgEnd(b)
b.Finish(obj)