Flatbuffer缓冲区始终为空

时间:2016-08-05 22:41:59

标签: c# flatbuffers

我有一个架构:

namespace ExampleApp.Assets.Communications;

table FlatServerToClientMessage {
  messageid:string;
  imagebytes:[ubyte];
}

root_type FlatServerToClientMessage;

为清楚起见,这里是ServerToClientMessage.cs

public class ServerToClientMessage : EventArgs
{
    public Guid MessageId { get; set; }
    public byte[] ImageBytes { get; set; }
}

我正在尝试通过TCP发送ServerToClientMessage。这在我使用JSON时工作正常,因此在其他地方不是问题。

我有一个FlatSerialize扩展方法,它应该序列化ServerToClientMessage并返回一个字节数组。但是,我的buffer.Data总是空的......它只是零。我的ServerToClientMessage确实有数据 - 它确实有MessageId和ImageBytes。

这是序列化扩展名:

 public static byte[] FlatSerialize(this ServerToClientMessage message) {
   var builder = new FlatBufferBuilder(1);

   //Create an ID
   var MessageId = builder.CreateString(message.MessageId.ToString());

   //Start the vector...
   //Loop over each byte and add it - my god, is there not a better way?
   FlatServerToClientMessage.StartImagebytesVector(builder, message.ImageBytes.Length);
   foreach(var imageByte in message.ImageBytes) {
    builder.AddByte(imageByte);
   }
   var imagebytes = builder.EndVector();

   //Start the FlatServerToClientMessage and add the MessageId and imagebytes
   FlatServerToClientMessage.StartFlatServerToClientMessage(builder);
   FlatServerToClientMessage.AddMessageid(builder, MessageId);
   FlatServerToClientMessage.AddImagebytes(builder, imagebytes);

   //End the FlatServerToClientMessage and finish it...
   var flatMessage = FlatServerToClientMessage.EndFlatServerToClientMessage(builder);
   FlatServerToClientMessage.FinishFlatServerToClientMessageBuffer(builder, flatMessage);

   var buffer = builder.DataBuffer;
   return buffer.Data;
  }

有没有人知道为什么我的buffer.Data只用零填充?

1 个答案:

答案 0 :(得分:2)

你的缓冲区不是空的,它不是从Offset中的偏移0开始(FlatBuffers是建立在前面的),它从FlatBufferBuilder.SizedByteArray()开始。您可以从那里访问字节。或者,您可以调用.split().tokenize("", 10).streaming()来创建仅包含FlatBuffer数据的字节数组。