How to serialize union of structs in Flatbuffers

对着背影说爱祢 提交于 2019-12-11 08:35:40

问题


Suppose I have the following Flatbuffers schema file:

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;

After I run flatc compiler on this schema file, the resulting weapon_generated.h file will have roughly the following structure:

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) { ... }

Notably, in order to use CreateWeaponDirect() or WeaponBuilder::add_properties(), I must pass the properties argument which must be of type flatbuffers::Offset<void>. What I don't understand however is how to create this object in the first place. As far as I can see, there is no function/method in the generated .h file that would return an object of this type. I can create an object of type PSword / PAxe / PMace of course, but how do I convert it into a flatbuffers Offset?


回答1:


You want FlatBufferBuilder::CreateStruct. This is indeed a bit weird compared to how you normally serialize structs (inlined), which is caused by unions wanting all union members to be the same size, so they are referenced over an offset.



来源:https://stackoverflow.com/questions/51272602/how-to-serialize-union-of-structs-in-flatbuffers

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!