title: Pass array of struct to C from C# via struct pointer
body: <p>I want to pass an array of struct from C# to C dll.</p>
  <p>The struct definition in C:</p>
  <pre><code>typedef struct{
      BYTE name[32];
      DWORD age;
  }DATA;
  </code></pre>
  <p>I marshalled the struct as follow:</p>
  <pre><code>[StructLayout(LayoutKind.Sequential)]
  public struct DATA
  {
      [MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)]
      public byte[] name;
      public int age;
  }
  </code></pre>
  <p>The C function definition that I want to pass on:</p>
  <pre><code>void test_data(DATA * pStruct, DWORD length){
      _tprintf(&quot;test start\n&quot;);
      
      if (!pData)
      {
          _tprintf(&quot;pData is NULL\n&quot;);
      }
      unsigned int i,j;
      
      for(i = 0; i &lt; length; i++){
          _tprintf(&quot;name: &quot;);
          for(j = 0; j &lt; 32; j++){
              _tprintf(&quot;%x &quot;,pData[i].name[j]);
          }
          _tprintf(&quot;\n&quot;);
          _tprintf(&quot;age: %d&quot;,pData[i].age);
          _tprintf(&quot;\n&quot;);
      }
  
      _tprintf(&quot;test finish\n&quot;);
  }
  </code></pre>
  <p>The function signature in C#:</p>
  <pre><code>[DllImport(&quot;a.dll&quot;, CallingConvention = CallingConvention.Cdecl)]
  public static extern void test_data(ref DATA pData, int length);
  </code></pre>
  <p>The setup in C#:</p>
  <pre><code>int length = 10;
  DATA[] arr = new DATA[length];
  for(int i = 0; i &lt; length; i++){
    arr[i].name = new byte[32];
    arr[i].age = 10;
  }
  
  test_data(ref arr[0], length);
  </code></pre>
  <p>But I got these output:</p>
  <pre><code>test start
  name: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
  age: 10
  name: 7c 67 9a 2 a 0 0 0 1 0 0 0 2 0 0 0 eb 9 77 67 a4 eb 8f 0 0 0 0 0 2 0 0 0
  age: 43673448
  test finish
  </code></pre>
  <p>The first one is correct, but the second one seems weird, and I think there is something wrong with how I passed the reference or doing the setup.</p>
  <p>I was inspired from the pinvoke web in SCardTransmit function <a href="https://www.pinvoke.net/default.aspx/winscard.SCardTransmit" rel="nofollow noreferrer">here</a> where it passed the byte array in C# to the <code>byte *</code> in C using <code>ref rapdu[0]</code></p>
  <p>How to correctly do this ?</p>