I tried to use a structure to analyze socket data when implementing a protocol based on UDP. And I searched, and I can use these 2 functions to convert between byte [] and 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); } }
Then I had this problem:
And struct to byte [] is the same. 2 ushort bytes canceled. How to solve this problem?
source share