问题
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