Do I need to free a managed BSTR used as a function parameter

c#, com

Solution

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. 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. As you can see is the caller responsible on allocating/deallocating the parameter string, outside the callee.

Problem

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? ``` public void WriteOutFile([In] [MarshalAs(UnmanagedType.BStr)] String data) { File.WriteAllText(fileName, data); //do I need the line below?? Marshal.FreeBSTR(data); } ``` Thanks

Original source