使用FlatBuffers编写结构体向量

4

我有以下的类:

命名空间为Message;

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()
2个回答

5
我们有一个关于Python端口未进行足够错误检查的开放问题:https://github.com/google/flatbuffers/issues/299msgStart之前应该创建字符串和向量。此外,您应该只使用一个Builder对象(仅使用b,而不是v),因为上面的代码从一个缓冲区引用到另一个缓冲区,这将无法正常工作。
编辑:现在Python实现在尝试嵌套向量/字符串/表生成时会正确地发出错误信号。然而,它仍然无法检测跨缓冲区偏移量。

3

我将分享我所做的事情,希望能帮助其他人(基于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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接