我是flatbuffers的新手,正在尝试创建一个带有嵌套向量的flatbuffers表。因为这不能根据flatbuffer规范来完成,所以我将外向量包装在另一个表中。以下是flatbuffers IDL:
namespace world;
table Point {
lat:double;
lon:double;
}
table Polygon {
vertices:[Point];
}
table Country {
id:int32;
area:[Polygon];
}
root_type Country;
然后我用python写了一个作家:
import flatbuffers
from world import Country, Polygon, Point
b = flatbuffers.Builder(0)
polys = []
for a in range(3):
points = []
for lon, lat in [[1,2], [3,4], [5,6]][:a+1]:
Point.PointStart(b)
Point.PointAddLat(b, lat + a*10)
Point.PointAddLon(b, lon + a*10)
t = Point.PointEnd(b)
points.append(t)
points.reverse()
Polygon.PolygonStartVerticesVector(b, len(points))
for p in points:
b.PrependUOffsetTRelative(p)
vertices = b.EndVector(len(points))
Polygon.PolygonStart(b)
Polygon.PolygonAddVertices(b, vertices)
Polygon.PolygonAddExtra(b, 1)
polys.append(Polygon.PolygonEnd(b))
polys.reverse()
Country.CountryStartAreaVector(b, len(polys))
for p in polys:
b.PrependUOffsetTRelative(p)
area = b.EndVector(len(polys))
Country.CountryStart(b)
Country.CountryAddArea(b, area)
pos = Country.CountryEnd(b)
b.Finish(pos)
raw_country = b.Output()
with open("output.pb", "wb") as out:
out.write(raw_country)
最后,我写信给读者:
import flatbuffers
import world.Country
with open("output.pb", "rb") as inf:
buf = bytearray(inf.read())
country = world.Country.Country.GetRootAsCountry(buf, 0)
for ii in range(country.AreaLength()):
poly = country.Area(ii)
print('[',poly.VerticesLength(), end=' ')
for jj in range(poly.VerticesLength()):
v = poly.Vertices(ii)
print('[{},{}]'.format(v.Lat(), v.Lon()), end=', ')
print(']')
(很抱歉有这么多代码——我尽量简化了事情)。 好吧,所以当我运行writer时,没有错误,一切看起来都很宏伟。不过,当我运行reader时,虽然没有得到任何错误,但也没有得到预期的输出。 而不是:
[1[2.0,1.0],]
[2[12.0,11.0],[14.0,13.0],]
[3[22.0,21.0],[24.0,23.0],[26.0,25.0],]
我得到:
[1[2.0,1.0],]
[2[14.0,13.0],[14.0,13.0],]
[3[26.0,25.0],[26.0,25.0],[26.0,25.0],]
换句话说,我得到的不是子向量中唯一的值,而是重复的值。我在C++中编写了同样的程序,结果也不一样,所以我认为这是一个与平板缓冲区的误解,而不是简单的错误。此外,当我移除外部向量(及其包装表)时,程序按预期工作。我有一长串不同的价值观。有人能看到我遗漏了什么吗?你知道吗
v = poly.Vertices(ii)
。。你是说v = poly.Vertices(jj)
?C++中有相同的吗?你知道吗相关问题 更多 >
编程相关推荐