Update: Answers to this question helped me code the open sourced project AlicanC\'s Modern Warfare 2 Tool on GitHub. You can see how I am reading these packets in MW
Well, you have two tasks here really. First is to interpret byte[] as struct essentially and second is to deal with possible different endianness.
So, they are somewhat diverge. AFAIK if you want to use marshaling - it will just interpret bytes as if it were managed structure. So converting from one endian to another is left to you. It is not hard to do but it will not be automatic.
So, to interpret byte[] as struct you have to have something like that:
[StructLayout(LayoutKind.Sequential)]
internal struct X
{
public int IntValue;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 3, ArraySubType = UnmanagedType.U1)]
public byte[] Array;
}
static void Main(string[] args)
{
byte[] data = {1, 0, 0, 0, 9, 8, 7}; // IntValue = 1, Array = {9,8,7}
IntPtr ptPoit = Marshal.AllocHGlobal(data.Length);
Marshal.Copy(data, 0, ptPoit, data.Length);
var x = (X) Marshal.PtrToStructure(ptPoit, typeof (X));
Marshal.FreeHGlobal(ptPoit);
Console.WriteLine("x.IntValue = {0}", x.IntValue);
Console.WriteLine("x.Array = ({0}, {1}, {2})", x.Array[0], x.Array[1], x.Array[2]);
}
So first 4 bytes go to IntValue (1,0,0,0) -> [little endian] -> 1 Next 3 bytes go directly to array.
If you want BigEndian you should do it yourself:
int LittleToBigEndian(int littleEndian)
{
byte[] buf = BitConverter.GetBytes(littleEndian).Reverse().ToArray();
return BitConverter.ToInt32(buf, 0);
}
It is somewhat messy like that, so probably for you will be better to stick with your custom-written parser that takes bytes one-by-one from source byte[] and fill your data class without StructLayout and other native interop.