Marshalling BSTRs from C++ to C# with COM interop

前端 未结 3 826
遇见更好的自我
遇见更好的自我 2021-01-12 16:30

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, a

3条回答
  •  被撕碎了的回忆
    2021-01-12 17:32

    I don't see an obvious problem with your code. Suggest you modify the ProcessRequest method to rule out COM interop as the source of the leak:

    HRESULT MyClass::ProcessRequest(BSTR request, BSTR* pResponse)
    {
        *psResponse = ::SysAllocStringLen(L"[suitably long string here]");
        return S_OK;
    }
    

    I suspect that won't leak, in which case you've narrowed the leak to your code.

    I'd also note the OLE2A allocates memory on the stack, so not only should you not delete pszRequest, but you shouldn't use OLE2A at all, due to the possibility of stack overflow. See this article for safer alternatives.

    I'd also suggest you replace A2BSTR with ::SysAllocString(CA2W(pszResponse))

提交回复
热议问题