UDP 기반 프로토콜을 구현할 때 소켓 데이터를 구문 분석하기 위해 구조체를 사용하려고했습니다. 가 내가 검색 한 내가 바이트 []와 구조체 사이의 변환이이 개 기능을 사용할 수 있습니다 C# byte []에서 struct로 변환 중입니다. 바이트 순서가 잘못되었습니다.
byte[] StructToBytes(object structObj)
{
int size = Marshal.SizeOf(structObj);
IntPtr buffer = Marshal.AllocHGlobal(size);
try
{
Marshal.StructureToPtr(structObj, buffer, false);
byte[] bytes = new byte[size];
Marshal.Copy(buffer, bytes, 0, size);
return bytes;
}
finally
{
Marshal.FreeHGlobal(buffer);
}
}
static object BytesToStruct(byte[] bytes, Type strcutType, int offset = 0)
{
int size = Marshal.SizeOf(strcutType);
IntPtr buffer = Marshal.AllocHGlobal(size);
try
{
Marshal.Copy(bytes, offset, buffer, size);
return Marshal.PtrToStructure(buffer, strcutType);
}
finally
{
Marshal.FreeHGlobal(buffer);
}
}
그런 다음 나는이 문제를 가지고 : 그냥 같은 [] 바이트
//I defined a simple struct with an ushort member
[StructLayout(LayoutKind.Sequential, Pack = 2)]
struct S
{
public ushort a;
}
//Then I define a byte[]
byte[] bArr;
bArr[0] = 0;
bArr[1] = 1;
//Convert to struct
S s = (S)BytesToStruct(bArr, typeof(S));
//Then s.a = 0x0100 not 0x0001
그리고 구조체이다 . ushort의 2 바이트가 반대로됩니다. 이 문제를 어떻게 해결합니까?