using System; using System.Diagnostics; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Drawing; namespace BlittableStructure { static class Program { static class Blittable where T : struct { public static readonly int Size = Marshal.SizeOf(typeof(T)); [ThreadStatic] public static readonly byte[] SrcBuffer = new byte[Size]; [ThreadStatic] public static readonly T[] DestBuffer = new T[1]; } static T Read(this Stream input) where T : struct { var size = Blittable.Size; var srcbuf = Blittable.SrcBuffer; var destbuf = Blittable.DestBuffer; if (input.Read(srcbuf, 0, size) < size) throw new EndOfStreamException(); var desthandle = GCHandle.Alloc(destbuf, GCHandleType.Pinned); try { var destptr = desthandle.AddrOfPinnedObject(); Marshal.Copy(srcbuf, 0, destptr, size); return destbuf[0]; } finally { desthandle.Free(); } } public static void Main() { var data = new byte[] { 0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x13, 0x45 }; using (var stream = new MemoryStream(data)) { var point = stream.Read(); Console.WriteLine("{0:X},{1:X}", point.X, point.Y); } } } }