title: C# Networking - Send struct buffer with StructLayout pack 1
body: <p>I have a server client program which is written by myself. I am using socket with TCP protocol. I am trying to send a buffer from the client to the server. That buffer is struct which I convert it to byte array send it and on the server I convert it back to struct from byte array:</p>
  
  <pre><code>    public static byte[] StructToByteArray(loginStruct obj)
      {
          int len = Marshal.SizeOf(typeof(loginStruct));
          byte[] arr = new byte[len];
  
          IntPtr ptr = Marshal.AllocHGlobal(len);
          Marshal.StructureToPtr(obj, ptr, true);
          Marshal.Copy(ptr, arr, 0, len);
  
          Marshal.FreeHGlobal(ptr);
          return arr;
  
      }
      public static void ByteArrayToStruct(byte[] buffer, ref loginStruct obj)
      {
          int len = Marshal.SizeOf(typeof(loginStruct));
  
          IntPtr i = Marshal.AllocHGlobal(len);
          Marshal.Copy(buffer, 0, i, len);
          obj = (loginStruct)Marshal.PtrToStructure(i, obj.GetType());
  
          Marshal.FreeHGlobal(i);
      }
  </code></pre>
  
  <p>My struct:</p>
  
  <pre><code>[StructLayout(LayoutKind.Sequential, Pack = 1)]
  struct loginStruct
  {
      public string userName;
      public string password;
  
      public loginStruct(string userName, string password)
      {
          this.userName = userName;
          this.password = password;
      }
  }
  </code></pre>
  
  <p>I got a runtime error on the line: </p>
  
  <pre><code>obj = (loginStruct)Marshal.PtrToStructure(i, obj.GetType());
  </code></pre>
  
  <p>The error is: </p>
  
  <blockquote>
    <p>Attempted to read or write protected memory. This is often an indication that other memory is corrupt.</p>
  </blockquote>
  
  <p>On the server in the function ByteArrayToStruct len is equals to the buffer size which is 16.</p>