title: PInvoke struct with array of unspecified length
body: <p><strong>C definitions</strong></p>
  
  <pre><code>typedef struct {
      const uint8_t* buf;
      int bufLen;
  } Info;
  
  
  int Foo(Info* info);
  </code></pre>
  
  <p><strong>C# definitions</strong></p>
  
  <pre><code>[StructLayout(LayoutKind.Sequential)]
  public struct Info
  {
       // [MarshalAs( ??? )]
       public byte[] buf;
       int bufLen
  }    
  
  [DllImport(...)]
  public static extern int Foo(ref Info info);
  </code></pre>
  
  <p>I'm having trouble figuring out what to specify for the <code>MarshalAs</code> attribute on <code>byte[] buf</code> in the C# struct definition. The buffer is allocated on the .NET side, and its length is known at call time.</p>
  
  <p>In a simple little test:</p>
  
  <pre><code>var info = new Info {
      buf = new byte[] {0x40, 0x50, 0x60, 0x70},
      bufLen = 4,
  };
  
  Foo(ref info);
  </code></pre>
  
  <p>Everything seems to be working correctly, but in fact the data in my buffer is incorrect.  Printing it out from the DLL I see <code>01 00 80 00</code> - not sure what that is.</p>
  
  <p>I've tried:</p>
  
  <ul>
  <li>No <code>MarshalAs</code></li>
  <li><code>[MarshalAs(UnmanagedType.SafeArray)]</code></li>
  </ul>
  
  <p>and nothing works.</p>
  
  <p>In general, I really don't know the best way to debug these kinds of problems either.</p>