// Collection of code snippets by Arne Vajhøj // (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) using System; using System.Runtime.InteropServices; class MainClass { private static byte[] ConvertStructToByte( object anything, ref byte rawsize) { rawsize = (byte)Marshal.SizeOf( anything ); IntPtr buffer = Marshal.AllocHGlobal( rawsize ); byte[] rawdatas = new byte[ rawsize ]; Marshal.StructureToPtr( anything, buffer, true ); Marshal.Copy( buffer, rawdatas, 0, rawsize ); Marshal.FreeHGlobal( buffer ); return rawdatas; } public static void test() { byte[] b; byte len = 0; X1 x1 = new X1(); x1.a = 123; x1.b = 123.456; b = ConvertStructToByte(x1, ref len); Console.WriteLine(len); for(int i = 0; i < len; i++) Console.Write(" " + b[i]); Console.WriteLine(); X2 x2 = new X2(); x2.a = 123; x2.b = 123.456; x2.c = "This is a test"; b = ConvertStructToByte(x2, ref len); Console.WriteLine(len); for(int i = 0; i < len; i++) Console.Write(" " + b[i]); Console.WriteLine(); X3 x3 = new X3(); x3.a = 123; x3.b = 123.456; x3.c = "This is a test"; x3.d = new short[5]; x3.d[0] = 1; x3.d[1] = 2; x3.d[2] = 3; x3.d[3] = 4; x3.d[4] = 5; b = ConvertStructToByte(x3, ref len); Console.WriteLine(len); for(int i = 0; i < len; i++) Console.Write(" " + b[i]); Console.WriteLine(); X4 x4 = new X4(); x4.a = 123; x4.b = 123.456; x4.c = "This is a test"; x4.d = new short[5]; x4.d[0] = 1; x4.d[1] = 2; x4.d[2] = 3; x4.d[3] = 4; x4.d[4] = 5; b = ConvertStructToByte(x4, ref len); Console.WriteLine(len); for(int i = 0; i < len; i++) Console.Write(" " + b[i]); Console.WriteLine(); } public static void Main(string[] args) { for(int i = 0; i < 1000; i++) { test(); } } } public struct X1 { public int a; public double b; } public struct X2 { public int a; public double b; public string c; } public struct X3 { public int a; public double b; public string c; public short[] d; } [StructLayout(LayoutKind.Sequential, Pack=1)] public struct X4 { public int a; public double b; public string c; [MarshalAs( UnmanagedType.ByValArray, SizeConst=5 )] public short[] d; }