title: Byte array to struct
body: <p>I'm having trouble converting the string parts of the byte array.</p>
  
  <p>My struct looks like this:</p>
  
  <pre><code>[StructLayout(LayoutKind.Sequential, Pack = 1)]
  struct Message
  {
      public int id;
  
      [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 10)]
      public string text;
  }
  </code></pre>
  
  <p>Creation of test byte array:</p>
  
  <pre><code>private static byte[] CreateMessageByteArray()
  {
      int id = 69;
      byte[] intBytes = BitConverter.GetBytes(id);
  
      string text = "test";
      byte[] stringBytes = GetBytes(text);
  
      IEnumerable&lt;byte&gt; rv = intBytes.Concat(stringBytes);
  
      return rv.ToArray();
  }
  </code></pre>
  
  <p>Method to convert my bytearray to a struct:</p>
  
  <pre><code>static T ByteArrayToStructure&lt;T&gt;(byte[] bytes) where T : struct
  {
      var handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
      var result = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T));
      handle.Free();
      return result;
  }
  </code></pre>
  
  <p>When I call <code>ByteArrayToStructure</code> with the result from <code>CreateMessageByteArray()</code> I get a struct with an id=60 and text="t".</p>
  
  <p>Why don't I get the whole string e.g "test" ?</p>
  
  <p>Edit:
  This is the code I forgot to pase:</p>
  
  <pre><code>    static byte[] GetBytes(string str)
      {
          byte[] bytes = new byte[str.Length * sizeof(char)];
          System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
          return bytes;
      }
  </code></pre>