【问题标题】:Writing a vector of struct with flatbuffers使用 flatbuffers 编写结构向量
【发布时间】:2015-11-02 16:19:23
【问题描述】:

我有以下课程:

命名空间消息;

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 flatbuffers


    【解决方案1】:

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

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

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

    【讨论】:

      【解决方案2】:

      我会给出我所做的,希望它可以帮助其他人(基于 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)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多