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

If I controlled a COM interface called from unmanaged code, can I free up 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

+4
source share
2 answers

You should not free the line because the caller can potentially reuse the transferred data, and if you are free, there may be an error. The reason is that FreeBSTR does not use the reference counting mechanism and simply calls SysFreeString , which, by the way, assumes that the line is allocated by one of the Sys(Re)Alloc... functions, a circumstance that you do not know about in managed code. The example shown here is interesting, imagine the unmanaged code calling you, this is this (from the link earlier):

 // 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 got put_StatusText(...) in managed code, we reproduce your situation. As you can see, the caller is responsible for highlighting / releasing the parameter string outside the callee.

+3
source

Marshalling involves copying data from unmanaged memory to managed memory. You do not need to free the string instance because it is a managed entity. But if you allocated memory in the native code before calling the callback, you need to free the memory in the native code after calling the callback.

+4
source

Source: https://habr.com/ru/post/1412122/


All Articles