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
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
FreeBSTRdoes not use any reference count mechanism and simply call SysFreeString, that by the way assumes that the string is allocated with one of the functionSys(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 ):
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.