using System.Runtime.InteropServices;
public static void Main()
MYSTRUCT1 s = new MYSTRUCT1();
s.a = 1; s.b = 2; s.c = 3;
Console.WriteLine("{0} {1} {2}",s.a,s.b,s.c);
byte[] buffer = StructToByteArray(s);
MYSTRUCT1 ss = new MYSTRUCT1();
ByteArrayToAnyStruct(ref ss, buffer);
Console.WriteLine("{0} {1} {2}",ss.a,ss.b,ss.c);
struct MYSTRUCT1 { public int a; public int b; public int c; }
struct MYSTRUCT2 { public int a; public string b; }
static byte[] StructToByteArray(object s)
byte[] data = new byte[Marshal.SizeOf(s)];
IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(s));
Marshal.StructureToPtr(s, ptr, true);
Marshal.Copy(ptr, data, 0, data.Length);
Marshal.FreeHGlobal(ptr);
static void ByteArrayToAnyStruct<T>(ref T s, byte[] buffer) where T : struct
IntPtr ptr = Marshal.AllocHGlobal(buffer.Length);
Marshal.Copy(buffer, 0, ptr, buffer.Length);
s = (T)Marshal.PtrToStructure(ptr, s.GetType());
Marshal.FreeHGlobal(ptr);