title: PInvoke: Allocate memory in C++ and free it in C#
body: <p>We are using PInvoke to interop between C# and C++. </p>
  
  <p>I have an interop struct as follows, with an identical layout C++ struct on the other side. </p>
  
  <pre><code>[StructLayout(LayoutKind.Sequential)]
  public struct MeshDataStruct : IDisposable
  {
      public MeshDataStruct(double[] vertices, int[] triangles , int[] surfaces)
      {
          _vertex_count = vertices.Length / 3;
          _vertices = Marshal.AllocHGlobal(_vertex_count*3*sizeof (double));
          Marshal.Copy(vertices, 0, _vertices, _vertex_count);
      }
  
      // .. extract data methods to double[] etc.
  
      private IntPtr _vertices;
      private int _vertex_count;
  
      public void Dispose()
      {
          if (_vertices != IntPtr.Zero)
          {
              Marshal.FreeHGlobal(_vertices);
              _vertices = IntPtr.Zero;
          }
      }
  }
  </code></pre>
  
  <p>Now I would like to add a second ctor </p>
  
  <pre><code>    public MeshDataStruct(bool filled_in_by_native_codee)
      {
          _vertex_count = 0;
          _vertices = IntPtr.Zero;
      }
  </code></pre>
  
  <p>and then write a method in C++ that allows C++ to fill in the data. This would allow us to use the same structure for input as well as output data...</p>
  
  <p>However, as far as I understand it, <code>AllocHGlobal</code> is available in C# and C++/Cli, but not pure C++. </p>
  
  <p>So my question is: How can I allocate memory in C++ such that I can safely free it on the C# side with a call to <code>Marshal.FreeHGlobal(...)</code>?</p>