title: Is Marshal.PtrToStructure on pointers that point to the native C++ heap sane?
body: <p>I have an application that marshals data between C# and C++ using PInvoke. The application is a native C++ app that starts the CLR with the C# part internally.</p>
  <p>At some point I have to marshal data from C++ to C# and I'm using <code>Marshal.PtrToStructure</code> for this. The C++ part basically looks like this:</p>
  <pre><code>struct X {};
  
  auto xPtr = new X; // somewhere in the application
  
  callCSharp(xPtr); // somewhere else
  </code></pre>
  <p>and the C# part like this:</p>
  <pre><code>public void callCSharp(IntPtr xPtr)
  {
      var x = Marshal.PtrToStructure&lt;X&gt;(xPtr);
  }
  </code></pre>
  <p>This code works on my Windows 10 machine but I'm not sure if I could run into trouble with this code. Lifetime management is all done in C++ so I don't have to allocate or free anything on C# side. However I'm not sure if the CLR can always access the native heap. <code>xPtr</code> is allocated using <code>new</code> and is therefore located on the native heap of the C++ application. <code>Marshal.PtrToStructure&lt;X&gt;(xPtr)</code> then tries to read memory at that location but I don't know if this can cause problems.</p>
  <p>I've read <a href="https://stackoverflow.com/a/36423272/6205379">this</a> which indicates that both the C++ application and the CLR use the same heap (<code>GetProcessHeap</code> that is) so this seems to support my findings for Windows 10, but it might be different for other OS versions.</p>
  <p>Is my sample code above sane? Are there any pitfalls here? Does this code work in Windows 7, 8 and 10?</p>