C#/Flatbuffers - How to make a ByteBuffer into byte[] and prefix it with ushort

Viewed 225

So basically here is how I do it with C++:

enum ServerOpcode : uint16_t{
    SERVER_AUTH_CONNECTION_RESPONSE                    = 0x001,
    SERVER_LOGIN_REQUEST_RESPONSE                      = 0x002,
    SERVER_NUM_MSG_TYPES                               = 0x003,
};

uint8_t* Vibranium::Packet::PreparePacket(ServerOpcode& serverOpcode, flatbuffers::FlatBufferBuilder& builder) {
    size_t size = builder.GetSize();
    uint8_t *buf = builder.GetBufferPointer();
    uint8_t *actualBuffer = new uint8_t[size + 2];
    actualBuffer[1] = (serverOpcode >> 8);
    actualBuffer[0] = (serverOpcode&0xFF);
    memcpy(actualBuffer + 2, buf, size);
    return actualBuffer;
}

I know that uint16_t is exactly 2 bytes and that is why i add +2.

Can someone give example in C# of how can I cast the ByteBuffer to byte[] and than prefix it with:

public enum ServerOpcode : ushort
{
    SERVER_AUTH_CONNECTION_RESPONSE                    = 0x001,
    SERVER_LOGIN_REQUEST_RESPONSE                      = 0x002,
    SERVER_NUM_MSG_TYPES                               = 0x003,

}

In C# I found out that the equivalent of uint16_t is ushort.

So my question is how can I convert ByteBuffer into byte[] and prefix it with ushort?

Can anyone make an answer showing and equivalent of PreparePacket in C# ?

P.S. Note that I am familiar with the file_identifier but I would like to do that manually. Hope someone can provide an example in C#

1 Answers

Following is the solution:

    public static Byte[] PrependServerOpcode(ByteBuffer byteBuffer, ServerOpcode code)
    {
        var originalArray = byteBuffer.ToArray(0, byteBuffer.Length);
        byte[] buffer = new byte[originalArray.Length + 2];
        buffer[0] = (byte)((ushort)code / 0x0100); 
        buffer[1] = (byte)code;
        Array.Copy(originalArray, 0, buffer, 2, originalArray.Length);
        return buffer;
    }

        public enum ServerOpcode : ushort
        {
            SERVER_AUTH_CONNECTION_RESPONSE = 0x001,
            SERVER_LOGIN_REQUEST_RESPONSE = 0x002,
            SERVER_NUM_MSG_TYPES = 0x003
        }

Or alternative:

public static ByteBuffer PrependServerOpcode(ByteBuffer byteBuffer, ServerOpcode code)
{
    var originalArray = byteBuffer.ToArray(0, byteBuffer.Length);
    byte[] buffer = new byte[originalArray.Length + 2];
    buffer[0] = (byte)((ushort)code / 0x0100);
    buffer[1] = (byte)code;
    Array.Copy(originalArray, 0, buffer, 2, originalArray.Length);
    return new ByteBuffer(buffer);
}

Usage:

    static void Main(string[] args)
    {
        var bb = new ByteBuffer(new byte[] { 0x01 });
        var result = PrependServerOpcode(bb, ServerOpcode.SERVER_NUM_MSG_TYPES);
    }
Related