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

前端 未结 3 824
遇见更好的自我
遇见更好的自我 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:27

    anelson has covered this pretty well, but I wanted to add a couple of points;

    • CoTaskMemAlloc is not the only COM-friendly allocator -- BSTRs are recognized by the default marshaller, and will be freed/re-allocated using SysAllocString & friends.

    • Avoiding USES_CONVERSION (due to stack overflow risks -- see anelson's answer), your full code should be something like this [1]

    (note that A2BSTR is safe to use, as it calls SysAllocString after conversion, and doesn't use dynamic stack allocation. Also, use array-delete (delete[]) as BuildResponse likely allocates an array of chars)

    • The BSTR allocator has a cache that can make it appear as though there is a memory leak. See http://support.microsoft.com/kb/139071 for some details, or Google for OANOCACHE. You could try disabling the cache and see if the 'leak' goes away.

    [1]

    HRESULT MyClass::ProcessRequest(BSTR request, BSTR* pResponse)
    {
        char* pszResponse = BuildResponse(CW2A(request));
        *pResponse = A2BSTR(pszResponse);
        delete[] pszResponse;
        return S_OK;
    }
    

提交回复
热议问题