John Jiang
John Jiang

Reputation: 955

How to build a vector of strings in python flatbuffer?

It appears that the python documentation (also this) for flatbuffer is currently spotty and mixed up with c++ api on occasions. I tried to create a vector of strings in the following manner:

builder, builder2, builder3 = flatbuffers.Builder(1024), flatbuffers.Builder(1024), flatbuffers.Builder(1024)
Feature.FeatureStart(builder)
Feature.FeatureStartStringValuesVector(builder2, 1)
builder2.PrependSOffsetTRelative(builder3.CreateString('a'.encode()))
Feature.AddStringValues(builder, builder2.EndVector(1))
Feature.FeatureEnd(builder)

At the line that has PrependSOffsetTRelative I get an error:

flatbuffers.builder.OffsetArithmeticError: flatbuffers: Offset arithmetic error.

I tried replacing builder3 with builder2, or replacing builder2/builder3 with builder, or removing .encode(), they all resulted in various errors.

I checked that the CreateString always returns 8 whereas PrependSOffsetTRelative seems to want only 0 as an input. What am I missing here? Thanks.

Here is my fbs schema file:

table Feature {
  string_values:[string];
}
root_type Feature;

Upvotes: 2

Views: 2151

Answers (1)

John Jiang
John Jiang

Reputation: 955

OK. I figured it out. There should not be multiple builders, instead the entire flatbuffer is constructed byte by byte directly in a sequence, from bottom to top, all using the same builder. So the order of calling Start, End etc methods matters a lot. The following works:

builder = flatbuffers.Builder(1024)
s = builder.CreateString('a')
Feature.FeatureStartStringValuesVector(builder, 1)
builder.PrependSOffsetTRelative(s)
x = builder.EndVector(1)
Feature.FeatureStart(builder)
Feature.FeatureAddStringValues(builder, x)
ret = Feature.FeatureEnd(builder)

Upvotes: 2

Related Questions