Search code examples
c#flatbuffers

How to retrieve field from any table in a flatbuffer schema


maybe this is a trivial question but...
I have a flatbuffer schema which defines some messages (tables).

enum EMessages : int
{
  E_MSG_EVENT_SYSTEM_INFO  = 0x8000,
  E_MSG_EVENT_SYSTEM_ERROR = 0x8001,
}


table  TMsgHeader
{
  sessionRef    : int;
  transactionId : int;
  status        : EStatus;
  source_id     : string;
}

table  MSG_EVENT_SYSTEM_INFO
{
  opcode        : EMessages  = E_MSG_EVENT_SYSTEM_INFO;
  header        : TMsgHeader;
  protocol_ver  : int = 100;
}

table  MSG_EVENT_SYSTEM_ERROR
{
  opcode        : EMessages  = E_MSG_EVENT_SYSTEM_ERROR;
  header        : TMsgHeader;
  error_no      : int;
  error_desc    : string;
}

On receiving side, I need a way to retrieve the OpCode field to know which message is (to deserialize it).
Cause, since every message has different size, the OpCode field is never in the same position on the binary buffer sent.

Is there some "best practice" applied to FlatBuffer?

I wanna avoid to encapsulate the FB payload into another message appending the OpCode.


Solution

  • You're best of using the built-in union feature, something like:

    union Message { Info, Error }
    table Info { protocol_ver:int }
    table Error { error_no:int; error_string:string }
    table Header { msg:Message; /* all other header fields go here */ }
    root_type Header
    

    See the documentation on how to serialize and read unions. What was previously opcode is now msg_type.