fork download
  1. using System;
  2. using System.Diagnostics;
  3. using System.IO;
  4. using System.Reflection;
  5. using System.Runtime.CompilerServices;
  6. using System.Runtime.InteropServices;
  7. using System.Drawing;
  8.  
  9. namespace BlittableStructure {
  10. static class Program {
  11. static class Blittable<T> where T : struct {
  12. public static readonly int Size = Marshal.SizeOf(typeof(T));
  13.  
  14. [ThreadStatic]
  15. public static readonly byte[] SrcBuffer = new byte[Size];
  16.  
  17. [ThreadStatic]
  18. public static readonly T[] DestBuffer = new T[1];
  19. }
  20.  
  21. static T Read<T>(this Stream input) where T : struct {
  22. var size = Blittable<T>.Size;
  23. var srcbuf = Blittable<T>.SrcBuffer;
  24. var destbuf = Blittable<T>.DestBuffer;
  25. if (input.Read(srcbuf, 0, size) < size)
  26. throw new EndOfStreamException();
  27. var desthandle = GCHandle.Alloc(destbuf, GCHandleType.Pinned);
  28. try {
  29. var destptr = desthandle.AddrOfPinnedObject();
  30. Marshal.Copy(srcbuf, 0, destptr, size);
  31. return destbuf[0];
  32. } finally {
  33. desthandle.Free();
  34. }
  35. }
  36.  
  37. public static void Main() {
  38. var data = new byte[] { 0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x13, 0x45 };
  39. using (var stream = new MemoryStream(data)) {
  40. var point = stream.Read<Point>();
  41. Console.WriteLine("{0:X},{1:X}", point.X, point.Y);
  42. }
  43. }
  44. }
  45. }
  46.  
Success #stdin #stdout 0.04s 24232KB
stdin
Standard input is empty
stdout
78563412,45131290