如何在Flatbuffers中序列化结构的并集 [英] How to serialize union of structs in Flatbuffers

查看:235
本文介绍了如何在Flatbuffers中序列化结构的并集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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;

在此架构文件上运行flatc编译器后,生成的weapon_generated.h文件将大致具有以下结构:

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

值得注意的是,为了使用CreateWeaponDirect()WeaponBuilder::add_properties(),我必须传递properties参数,该参数必须为flatbuffers::Offset<void>类型.但是我不了解的是如何首先创建该对象.据我所知,在生成的.h文件中没有函数/方法可以返回这种类型的对象.我当然可以创建PSword/PAxe/PMace类型的对象,但是如何将其转换为Flatbuffers偏移量?

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?

推荐答案

您要FlatBufferBuilder::CreateStruct.与通常序列化结构(内联)的方式相比,这确实有点怪异,这是由于工会希望所有工会成员的大小相同,因此要在偏移量上引用它们.

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.

这篇关于如何在Flatbuffers中序列化结构的并集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆