Search code examples
c#c++flatbuffers

SystemAccessOutOfbound Exception while trying to access "LengthofTable" from flatbuffer's binary file


I'm storing my data according to following schema.

namespace iCalendarParser;

table EventParsed {

UID:string;
Organizer:string;
Summary:string;
Description:string;
Attendee:[string];
Categories:string;
DtEnd:string;
DtStart:string;
DtStamp:string;
AttendeeCounter:short;

}

table TableofEvents{

  events:[EventParsed];

}

root_type TableofEvents;

I'm storing data like this in my c++ application.

   std::vector<flatbuffers::Offset<flatbuffers::String>> ListOfAttendee;
   std::vector<flatbuffers::Offset<iCalendarParser::EventParsed>> ListofEvents;



    for (auto EventList : ListofAllEvents)
    {

auto Organizer = builder.CreateString(EventList->Organizer);
auto UID = builder.CreateString(EventList->UID);
auto DtStart = builder.CreateString(EventList->DtStart);
auto DtEnd = builder.CreateString(EventList->DtEnd);
auto DtStamp = builder.CreateString(EventList->DtStamp);
auto Summary = builder.CreateString(EventList->Summary);
auto Description = builder.CreateString(EventList->Description);
auto Categories = builder.CreateString(EventList->Categories);

for (int i = 0; i < EventList->AttendeeCounter; i++)
{
    ListOfAttendee.push_back(builder.CreateString(EventList->Attendee[i]));

}


auto VectorListofAttendee = builder.CreateVector(ListOfAttendee);

auto CreatEventInFlatBuffer = CreateEventParsed(builder, UID, Organizer, Summary, Description, VectorListofAttendee, Categories, DtEnd, DtStart, DtStamp, EventList->AttendeeCounter);

ListofEvents.push_back(CreatEventInFlatBuffer);

 }

 auto CreatVectorOfEventInFlatbuffer = builder.CreateVector(ListofEvents);
 auto InsertEventInFlatBufferList = CreateTableofEvents(builder, 
 CreatVectorOfEventInFlatbuffer);
 builder.Finish(InsertEventInFlatBufferList);

 uint8_t *buf = builder.GetBufferPointer();
 int size = builder.GetSize();

 std::ofstream ofile("icalBin.bin", std::ios::binary);
 ofile.write((char *)&buf, size);
 ofile.close();

From my C# application I'm trying to access the deserialize the data.

byte[] ReadbytesfromFile = File.ReadAllBytes("icalBin.bin");
var buffer = new ByteBuffer(ReadbytesfromFile);
var tableofEvents = TableofEvents.GetRootAsTableofEvents(buffer); 
int len = tableofEvents.EventsLength;

I can not figure out what is wrong. Can anyone tell me how can I access nested tables according to schema and deserialize into C#.

General idea:

1.Get listofevents.

2.Access individual events struct. (The result I'm trying to get)


Solution

  • I see 2 problems in your code:

    • It's missing a ListOfAttendee.clear(), your nested loops are causing this list to grow bigger on each iteration.
    • You are writing pointer data to a file, not what the pointer is pointing to (remove the &).