title: Reading a C/C++ data structure in C# from a byte array
body: <p>What would be the best way to fill a C# struct from a byte[] array where the data was from a C/C++ struct?  The C struct would look something like this (my C is very rusty):</p>
  
  <pre><code>typedef OldStuff {
      CHAR Name[8];
      UInt32 User;
      CHAR Location[8];
      UInt32 TimeStamp;
      UInt32 Sequence;
      CHAR Tracking[16];
      CHAR Filler[12];
  }
  </code></pre>
  
  <p>And would fill something like this:</p>
  
  <pre><code>[StructLayout(LayoutKind.Explicit, Size = 56, Pack = 1)]
  public struct NewStuff
  {
      [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 8)]
      [FieldOffset(0)]
      public string Name;
  
      [MarshalAs(UnmanagedType.U4)]
      [FieldOffset(8)]
      public uint User;
  
      [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 8)]
      [FieldOffset(12)]
      public string Location;
  
      [MarshalAs(UnmanagedType.U4)]
      [FieldOffset(20)]
      public uint TimeStamp;
  
      [MarshalAs(UnmanagedType.U4)]
      [FieldOffset(24)]
      public uint Sequence;
  
      [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)]
      [FieldOffset(28)]
      public string Tracking;
  }
  </code></pre>
  
  <p>What is best way to copy <code>OldStuff</code> to <code>NewStuff</code>, if <code>OldStuff</code> was passed as byte[] array?</p>
  
  <p>I'm currently doing something like the following, but it feels kind of clunky.</p>
  
  <pre><code>GCHandle handle;
  NewStuff MyStuff;
  
  int BufferSize = Marshal.SizeOf(typeof(NewStuff));
  byte[] buff = new byte[BufferSize];
  
  Array.Copy(SomeByteArray, 0, buff, 0, BufferSize);
  
  handle = GCHandle.Alloc(buff, GCHandleType.Pinned);
  
  MyStuff = (NewStuff)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(NewStuff));
  
  handle.Free();
  </code></pre>
  
  <p>Is there better way to accomplish this?</p>
  
  <hr>
  
  <p>Would using the <code>BinaryReader</code> class offer any performance gains over pinning the memory and using <code>Marshal.PtrStructure</code>?</p>