title: Marshal struct with array member in C#
body: <p>I'm using C# with P/Invoke to access to a DLL method. The definition of the method is the following:</p>
  
  <pre><code>[DllImport("userManager.dll")]
  static extern int GetUsers(out IntPtr userList);
  </code></pre>
  
  <p>Original structs:</p>
  
  <pre><code>typedef struct user_list {
     unsigned short NumUsers;
     USER_LIST_ITEM List[VARLEN];
  } USER_LIST
  
  typedef struct user_list_item {
     char name[260];
     unsigned char address[256];
  } USER_LIST_ITEM
  </code></pre>
  
  <p>And the struct layout I've done is the following:</p>
  
  <pre><code>[StructLayout(LayoutKind.Sequential)]
  public class USER_LIST
  {
      public uint NumUsers;
      [MarshalAs(UnmanagedType.ByValArray)]
      public USER_LIST_ITEM [] List;
  }
  
  [StructLayout(LayoutKind.Sequential)]
  public class USER_LIST_ITEM
  {
      [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
      public string name;
      [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
      public string address;
  };
  </code></pre>
  
  <p>But I get an error when I try to unmarshall it:</p>
  
  <pre><code>USER_LIST userList = new USER_LIST();
  // Prepare pointer 
  IntPtr uList = Marshal.AllocHGlobal(Marshal.SizeOf(userList));
  Marshal.StructureToPtr(userList, uList, false);
  result = GetUsers(out uList);
  
  Marshal.PtrToStructure(uList, userList); &lt;--
  </code></pre>
  
  <blockquote>
    <p>The runtime has encountered a fatal error. The address of the error was at 0x79f82af6, on thread 0x464. The error code is 0xc0000005. This error may be a bug in the CLR or in the unsafe or non-verifiable portions of user code. Common sources of this bug include user marshaling errors for COM-interop or PInvoke, which may corrupt the stack.</p>
  </blockquote>
  
  <p>I get the NumUsers property right, but it seems the error occurs when unmarshalling the array. Any thoughts?</p>