[英]Do I need to free a managed BSTR used as a function parameter
If I have managed COM interface called from unmanaged code, am I responsible for freeing up the memory after use or will it be handled by garbage collection? 如果我管理了从非托管代码调用的COM接口,我是否负责在使用后释放内存或者它将由垃圾收集处理?
public void WriteOutFile([In] [MarshalAs(UnmanagedType.BStr)] String data)
{
File.WriteAllText(fileName, data);
//do I need the line below??
Marshal.FreeBSTR(data);
}
Thanks 谢谢
Marshalling involves copying the data from unmanaged memory to managed memory. 编组涉及将数据从非托管内存复制到托管内存。 You don not need to free the
string
instance because it's a managed object. 您不需要释放
string
实例,因为它是一个托管对象。 But if you allocate memory in the native code before the callback call, you need to free the memory in the native code after the callback call. 但是如果在回调调用之前在本机代码中分配内存,则需要在回调调用之后释放本机代码中的内存。
You should not free the string because the caller can potentially reuse the data passed and if you free it is possible to have a fault. 您不应该释放字符串,因为调用者可能会重用传递的数据,如果您释放它可能会出错。 The reason is that
FreeBSTR
does not use any reference count mechanism and simply call SysFreeString , that by the way assumes that the string is allocated with one of the function Sys(Re)Alloc...
, circumstance you are not aware of in the managed code. 原因是
FreeBSTR
不使用任何引用计数机制并简单地调用SysFreeString ,顺便说一下,假定该字符串分配了一个函数Sys(Re)Alloc...
,在托管中你不知道的情况码。 The example shown here is interesting, imagin the unmanaged code calling you is this one ( from the link before ): 这里显示的例子很有趣,想象一下,调用你的非托管代码就是这个(来自之前的链接):
// shows using the Win32 function
// to allocate memory for the string:
BSTR bstrStatus = ::SysAllocString(L"Some text");
if (bstrStatus != NULL)
{
pBrowser->put_StatusText(bstrStatus);
// Free the string:
::SysFreeString(bstrStatus);
}
and you have imlemented put_StatusText(...)
in your managed code we are reproducing your situation. 并且您在托管代码中嵌入了
put_StatusText(...)
,我们正在重现您的情况。 As you can see is the caller responsible on allocating/deallocating the parameter string, outside the callee. 正如您所看到的那样,调用者负责在被调用者之外分配/解除分配参数字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.