C#/Flatbuffers-如何将ByteBuffer转换为byte[]并在其前面加上ushort
基本上我是用C++实现的:C#/Flatbuffers-如何将ByteBuffer转换为byte[]并在其前面加上ushort,c#,flatbuffers,C#,Flatbuffers,基本上我是用C++实现的: enum ServerOpcode : uint16_t{ SERVER_AUTH_CONNECTION_RESPONSE = 0x001, SERVER_LOGIN_REQUEST_RESPONSE = 0x002, SERVER_NUM_MSG_TYPES = 0x003, }; uint8_t* V
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;
}
我知道uint16\u t
正好是2个字节,这就是我添加+2
的原因
有人能用C#举例说明如何将ByteBuffer
转换为byte[]
并在其前面加上前缀:
public enum ServerOpcode : ushort
{
SERVER_AUTH_CONNECTION_RESPONSE = 0x001,
SERVER_LOGIN_REQUEST_RESPONSE = 0x002,
SERVER_NUM_MSG_TYPES = 0x003,
}
在C中,我发现uint16\u t
的等价物是ushort
因此,我的问题是如何将ByteBuffer
转换为byte[]
并在其前面加上ushort
任何人都可以在C#
中给出一个显示和等效于preparePackage
的答案吗
附言。
请注意,我熟悉
文件\u标识符
,但我想手动完成。希望有人能在C#中提供一个例子,以下是解决方案:
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
}
或替代方案:
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);
}
用法:
static void Main(string[] args)
{
var bb = new ByteBuffer(new byte[] { 0x01 });
var result = PrependServerOpcode(bb, ServerOpcode.SERVER_NUM_MSG_TYPES);
}
ByteBuffer
是flatbuffers类。我也不是在读小溪里的书。我在C++示例中从平板缓冲区的构建器中阅读。@ Veelin编辑了我的答案,使用了平面缓冲区/ByTeffelApHythyYu@ pk,但是我认为函数