title: Initializing a C# IntPtr to accept data from unmanaged C++ DLL?
body: <p>I have an exported function in unmanaged C++ code that expects a pointer to a BStr, where it will write some text data (258 bytes, max)</p>
  
  <pre><code>extern "C" __declspec(dllexport)
  int CppFunc(BSTR *data)
  { ... }
  </code></pre>
  
  <p>I want that data as a string.</p>
  
  <p>This works</p>
  
  <pre><code>[DllImport( ... CallingConvention = CallingConvention.Cdecl)]
  public static extern int CppFunc([MarshalAs(UnmanagedType.BStr)] ref string data);
  </code></pre>
  
  <p>but it creates a memory leak.</p>
  
  <p>I assume what I should be doing is creating and passing an IntPtr, then Marshal out the Bstr as a string, then free the IntPtr:</p>
  
  <pre><code>IntPtr p = Marshal.AllocHGlobal(512);
  CppFunction(p);
  string data = Marshal.PtrToStringBSTR(p);
  Marshal.FreeHGlobal(p) ;
  </code></pre>
  
  <p>The problem is, with that code, I get a System.AccessViolationException on the call into Marshal.PtrToStringBSTR(p).</p>
  
  <p>What am I doing wrong?!</p>