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

别等时光非礼了梦想. 提交于 2019-12-01 04:25:37

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;
}

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))

I guess you need to destroy request with ::SysFreeString(). This memory is allocated on server side.

Also, OLE2A may allocate memory due to conversion (take a look). You do not free it also.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!