flatbuffers

How can I avoid circular header dependencies when using native_type with flatbuffers?


The documentation states the following:

The native_type attribute will replace the usage of the generated class with the given type. So, continuing with the example, the generated code would use vector2 in place of Vec2T for all generated code of the Object-Based API. However, because the native_type is unknown to flatbuffers, the user must provide the following functions to aide in the serialization process:

namespace flatbuffers {
   Vec2 Pack(const vector2& obj);
   vector2 UnPack(const Vec2& obj);
}

And then:

native_include("path") (at file level): Because the native_type attribute can be used to introduce types that are unknown to flatbuffers, it may be necessary to include "external" header files in the generated code. This attribute can be used to directly add an include directive to the top of the generated code that includes the specified path directly.

So if I understood anything, I'm supposed to "native_include" the header where vector2 is declared so that the generated header file will have it. Good.

But then, where am I supposed to declare the Pack/UnPack functions?! Those are also needed by the generated header, so those should be included as well... But those declarations require the definition of the type Vec2, which is defined in the generated code. So either this is a circular dependency, and it's impossible to use the feature, or am I missing something crucial?


Solution

  • Turns out I can forward-declare the return type even when it's not a pointer.

    So here's what I did:

    struct Vec2;
    namespace flatbuffers {
        Vec2 Pack(const vector2& obj);
        vector2 UnPack(const Vec2& obj);
    }