title: P-Invoke Unmarshalling an array of structs allocated in a DLL
body: <p>I have a requirement to shovel large amounts (theoretically up to a few terabytes, only limited by available memory) of data from a C/C++ based core DLL which manages, filters and allocates the data, to a C# GUI (which only reads the data). It would be optimal if the data are never duplicated but only accessed per reference from the C#. The signature of my DLL's method is currently the following (I can make changes there):</p>
  
  <pre><code>extern "C" {
  
  typedef struct {
      wchar_t* name;
      __int32 t;
      float v;
      bool condition;
  
      } TestData;
  
  __declspec(dllexport) void fillTestArrayWithAlloc(TestData** td, __int32* size);
  };
  </code></pre>
  
  <p>The array length is not known to C# and can be anything between 1 and millions....</p>
  
  <p>I mapped the structure like this:</p>
  
  <pre><code>   [StructLayout(LayoutKind.Sequential)]
     struct TestData
      {
          [MarshalAs(UnmanagedType.LPWStr)]
          public String name;
          public Int32 t;
          [MarshalAs(UnmanagedType.R4)]
          public float v; 
          public bool condition;
  
      }
  </code></pre>
  
  <p>I tried both manual unmarshalling like this</p>
  
  <pre><code>static extern void fillTestArrayWithAlloc(ref IntPtr td, ref int size);
  </code></pre>
  
  <p>and automatic unmarshalling like this</p>
  
  <pre><code>static extern void fillTestArrayWithAlloc([Out] TestData[] td, ref int size);
  </code></pre>
  
  <p>But in both cases it performs a memory copy, which is undesired. Is there a way to do it without a data copy?</p>
  
  <p>Best regards
  Petr</p>