BSTR 分配器有一个缓存,可以使它看起来好像存在内存泄漏.有关详细信息,请参阅 http://support.microsoft.com/kb/139071 或 Google对于OANOCACHE.您可以尝试禁用缓存,看看泄漏"是否消失.[1]HRESULT MyClass::ProcessRequest(BSTR request, BSTR* pResponse){char* pszResponse = BuildResponse(CW2A(request));*pResponse = A2BSTR(pszResponse);删除[] pszResponse;返回 S_OK;}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.Simplifying a bit, the IDL for the server method isHRESULT ProcessRequest([in] BSTR request, [out] BSTR* pResponse);and the implementation looks like: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;}A2BSTR internally allocates the BSTR using SysAllocStringLen().In the C# client I simply do the following:string request = "something";string response = "";myserver.ProcessRequest(request, out response);DoSomething(response);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 server 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.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.Andy 解决方案 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;} 这篇关于使用 COM 互操作将 BSTR 从 C++ 编组到 C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-20 02:56