// 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.IO; using System.Runtime.InteropServices; namespace Alternative { [StructLayout(LayoutKind.Sequential,CharSet=CharSet.Ansi)] public class Data { [MarshalAs(UnmanagedType.I4)] public int Id; [MarshalAs(UnmanagedType.I2)] public short V1; [MarshalAs(UnmanagedType.I2)] public short V2; [MarshalAs(UnmanagedType.ByValTStr,SizeConst=8)] public string S; public override string ToString() { return string.Format("({0},{1},{2},{3})", Id, V1, V2, S); } } public class Program { public static void Main(string[] args) { byte[] b = { 0x01, 0x00, 0x00, 0x00, // Id = 1 0x01, 0x00, // V1 = 1 0x02, 0x00, // V2 = 2 0x41, 0x42, 0x43, 0x00, 0x00, 0x00, 0x00, 0x00, // S = "ABC" 0x002, 0x00, 0x00, 0x00, // Id = 2 0x02, 0x00, // V1 = 2 0x03, 0x00, // V2 = 3 0x41, 0x42, 0x43, 0x44, 0x45, 0x00, 0x00, 0x00 }; // S = "ABCDE" int bufsiz = Marshal.SizeOf(typeof(Data)); IntPtr buf = Marshal.AllocHGlobal(bufsiz); int ix = 0; while(ix < b.Length) { Marshal.Copy(b, ix, buf, bufsiz); Data o = (Data)Marshal.PtrToStructure(buf, typeof(Data)); Console.WriteLine(o); ix += bufsiz; } Marshal.FreeHGlobal(buf); } } }