用flatbuffer编写结构向量

2024-10-01 09:16:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下几门课:

名称空间消息

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

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

root_type Message;

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

^{pr2}$

不会出错

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

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

Tags: 名称消息空间msgfloatstructprintxmin
2条回答

我会付出我所做的,希望它能帮助其他人(基于Aardapel的回答)

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)

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

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

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

相关问题 更多 >