Note that there are some explanatory texts on larger screens.

plurals
  1. POMarshalling BSTRs from C++ to C# with COM interop
    primarykey
    data
    text
    <p>I have an out-of-process COM server written in C++, which is called by some C# client code. A method on one of the server's interfaces returns a large BSTR to the client, and I suspect that this is causing a memory leak. The code works, but I am looking for help with marshalling-out BSTRs.</p> <p>Simplifying a bit, the IDL for the server method is</p> <pre><code>HRESULT ProcessRequest([in] BSTR request, [out] BSTR* pResponse); </code></pre> <p>and the implementation looks like:</p> <pre><code>HRESULT MyClass::ProcessRequest(BSTR request, BSTR* pResponse) { USES_CONVERSION; char* pszRequest = OLE2A(request); char* pszResponse = BuildResponse(pszRequest); delete pszRequest; *pResponse = A2BSTR(pszResponse); delete pszResponse; return S_OK; } </code></pre> <p>A2BSTR internally allocates the BSTR using SysAllocStringLen().</p> <p>In the C# client I simply do the following:</p> <pre><code>string request = "something"; string response = ""; myserver.ProcessRequest(request, out response); DoSomething(response); </code></pre> <p>This works, in that request strings get sent to the COM server and correct response strings are returned to the C# client. But every round trip to the server leaks memory in the <em>server</em> process. The crt leak detection support is showing no significant leaks on the crt heap, so I'm suspecting the leak was allocated with IMalloc.</p> <p>Am I doing anything wrong here? I have found vague comments that 'all out parameters must be allocated with CoTaskMemAlloc, otherwise the interop marshaller won't free them' but no details.</p> <p>Andy</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload