Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FlatBuffers: Send Multiple Packet Types Using a Union

I will be sending multiple buffer types over a connection. To keep it simple, imagine a schema like:

namespace MyEvents;  

table EventOne  
{  
  id:uint;  
  timestamp:ulong;  
  adress:string;  
}  

table EventTwo  
{  
  id:uint;  
  timestamp:ulong; 
  strength:float;   
}  

union Events {EventOne, EventTwo}  

table EventHolder  
{  
  theEvent:Events;  
}  

root_type EventHolder;  

I generate the needed files for C++ and C#, and include them as required in my respective projects.

Here is how I am encoding events in C++ - here, an event of type EventOne:

...  
uint32_t anId(645);  
uint64_t aTimestamp(1234567);  
string anAddress("00::00::45::56::47::e5");  

flatbuffers::FlatBufferBuilder builder;  
auto addressOffset= builder.CreateString(anAddress);  
auto eventOneOffset= MyEvents::CreateEventOne(builder, anId, aTimestamp, addressOfset);   

// Here is where I am confused - how to create the EventHolder object.  
// Original code I posted about - commented out, but has error.
//auto eventHolderOffset= MyEvents::CreateEventHolder(builder, MyEvents::Events_EventOne, eventOneOffset);  // Compile error here.  

auto eventHolderOffset= MyEvents::CreateEventHolder(builder, MyEvents::Events_EventOne, eventOneOffset.Union());  // No compile error here.  

builder.Finish(eventHolderOffset);  

// Access buffer pointer and size and send it on its way.  

Note that I have a problem with creating the EventHolder object: I have an offset that is type FlatBuffers::Offset<MyEvents::EventOne> but the CreateEventHolder function takes an offset of type FlatBuffers::Offset<void>.

  • Is this procedure (table containing object of union type) the proper way to send multiple packet types using flatbuffers? EDIT: Answer seems to be "yes"
  • Am I missing an inside-out encoding step for theEvent? EDIT: No! It works great.
  • If this procedure is right, what do I need to do to avoid the type conflict? EDIT: Like Aardappel said, and from Flatbuffers encoding then decoding C++ double array + table + union returns junk, I just needed to add .Union() to the offset argument.

Any help would be appreciated. FWIW, I am encoding in C++, and doing test decoding there, but sending data over UDP to a C# application to do the final decoding there. On that end, I do a type test on the packet and interpret accordingly.

Update: I found an example, and saw that I need to add the Union function to the end of my offset in CreateEventHolder. I may be good to go now.

like image 269
GTAE86 Avatar asked Jun 07 '16 16:06

GTAE86


1 Answers

Try eventOneOffset.Union() to get the untyped version of that offset. Maybe this is not documented well enough.

like image 188
Aardappel Avatar answered Nov 05 '22 09:11

Aardappel