从部分填充的 flatbuffer 添加或修改 nullptr Vector?

Add or modify a nullptr Vector from a partially filled flatbuffer?

这是建立在怪物模式示例的基础上的。如果我像官方 test.cpp.

那样部分填充了一个 flatbuffer

下面也复制了相关行

// Create a mostly empty FlatBuffer.
flatbuffers::FlatBufferBuilder nested_builder;
auto nmloc = CreateMonster(nested_builder, nullptr, 0, 0,
                           nested_builder.CreateString("NestedMonster"));
FinishMonsterBuffer(nested_builder, nmloc);

如何在已经调用 FinishMonsterBuffer(nested_builder, nmloc); 之后修改 nested_builder 模式的清单部分?

我尝试过的事情(与test.cpp相关):

std::string bfbsfile;
bool found = flatbuffers::LoadFile( "./monster_schema.bfbs", true, &bfbsfile );
const reflection::Schema& schema = *reflection::GetSchema( bfbsfile.c_str() );
auto root_table = schema.root_table();

auto fields = root_table->fields();

// The above works fine I've tested the fields and verified the schema.
// I'm unsure of the code below.

// First we put the FlatBuffer inside an std::vector.
std::vector<uint8_t> resizingbuf(
    nested_builder.GetBufferPointer(), 
    nested_builder.GetBufferPointer() + nested_builder.GetSize());
// Get the root.
// This time we wrap the result from GetAnyRoot in a smartpointer that
// will keep rroot valid as resizingbuf resizes.
auto rroot = flatbuffers::piv(flatbuffers::GetAnyRoot(resizingbuf.data()),
                              resizingbuf);
// Now lets try to extend a vector by 100 elements (0 -> 110).
auto &inventory_field = *fields->LookupByKey("inventory");
// I don't think this works either if it doesn't already exist.
auto rinventory = flatbuffers::piv(
     flatbuffers::GetFieldV<uint8_t>(**rroot, inventory_field), resizingbuf);

// This line silently fails probably because *rinventory is probably a nullptr  
// but I don't know how to set it after having already 
// called FinishMonsterBuffer(nested_builder, nmloc);.
flatbuffers::ResizeVector<uint8_t>(schema, 110, 50, *rinventory,
                                   &resizingbuf);
// Try to print it but prints nothing.
// printf("%hhu", rinventory->Get(10));

提前为标题道歉我不太确定如何表达确切的问题或疑问。 如果需要更多上下文或部分问题没有意义,请告诉我。

免责声明:Flatbuffers 通常不允许在缓冲区完成后改变向量。然而,我们在反射 API 中确实有一些高级 API 用于进行此类突变,但通常速度较慢且不推荐。

我们不支持调整 null 矢量的大小。我们将 null 存储在 vtable 中,并且在与 null 向量相关的缓冲区中没有 data/size 信息。因此没有什么可以调整的。

您可以尝试插入一个空向量,因为这应该将必要的 data/size 信息放入缓冲区,稍后可以调整大小。