title: Why can I not use Marshal.Copy() to update a struct?
body: <p>I have some code intended to get a struct from a byte array:</p>
  
  <pre><code>    public static T GetValue&lt;T&gt;(byte[] data, int start) where T : struct
      {
          T d = default(T);
          int elementsize = Marshal.SizeOf(typeof(T));
  
          GCHandle sh = GCHandle.Alloc(d, GCHandleType.Pinned);
          Marshal.Copy(data, start, sh.AddrOfPinnedObject(), elementsize);
          sh.Free();
  
          return d;
      }
  </code></pre>
  
  <p>However, the structure <code>d</code> is never modified, and always returns its default value.</p>
  
  <p>I have looked up the 'correct' way to do this and am using that instead, but am still curious, as I cannot see why the above should not work.</p>
  
  <p>Its as simple as can be: allocate some memory, d, get a pointer to it, copy some bytes into the memory pointed at by this, return.
  Not only that, <strong>but when I use similar code but with d being an array of T, it works fine.</strong>
  Unless sh.AddrOfPinnedObject() isn't really pointing to <code>d</code>, but then what is the point of it? </p>
  
  <p><strong>Can anyone tell me why the above does not work?</strong></p>