如何在 Flatbuffers 中序列化结构的并集

How to serialize union of structs in Flatbuffers

假设我有以下 Flatbuffers 模式文件:

union WeaponProperties {
    sword:  PSword,
    axe:    PAxe,
    mace:   PMace,
}
struct PSword { length: float32; straight: bool; }
struct PAxe   { bearded: bool; }
struct PMace  { hardness: int8; }

table Weapon {
    name:      string;
    mindamage: int32;
    maxdamage: int32;
    swingtime: float32;
    weight:    float32;
    properties: WeaponProperties;
}
root_type Weapon;

在我运行 flatc编译这个模式文件后,生成的weapon_generated.h文件将具有大致如下结构:

enum WeaponProperties {
  WeaponProperties_NONE = 0,
  WeaponProperties_sword = 1,
  WeaponProperties_axe  = 2,
  WeaponProperties_mace = 3,
  ...
};
struct PSword { ... }
struct PAxe   { ... }
struct PMace  { ... }

class Weapon { ... }
class WeaponBuilder { ... }

inline flatbuffers::Offset<Weapon> CreateWeaponDirect(
    flatbuffers::FlatBufferBuilder &_fbb,
    const char *name = nullptr,
    int32_t mindamage = 0,
    int32_t maxdamage = 0,
    float swingtime = 0.0f,
    float weight = 0.0f,
    WeaponProperties properties_type = WeaponProperties_NONE,
    flatbuffers::Offset<void> properties = 0) { ... }

值得注意的是,为了使用 CreateWeaponDirect()WeaponBuilder::add_properties(),我必须传递类型为 flatbuffers::Offset<void>properties 参数。然而,我不明白的是如何首先创建这个对象。据我所知,在生成的 .h 文件中没有 function/method 会 return 这种类型的对象。我当然可以创建 PSword / PAxe / PMace 类型的对象,但是如何将其转换为平面缓冲区偏移量?

你想要FlatBufferBuilder::CreateStruct。与您通常序列化结构(内联)的方式相比,这确实有点奇怪,这是由联合希望所有联合成员大小相同,因此它们是通过偏移量引用的。