all groups > dotnet interop > august 2006 >
You're in the

dotnet interop

group:

Will SysAllocString allocation be GC'ed


Will SysAllocString allocation be GC'ed Peggy
8/29/2006 2:10:15 AM
dotnet interop:
Hi

I have an unmanaged dll which returns a BSTR* allocated using a
SysAllocString on the unmanaged code.

Now when this BSTR is returned to the Managed world, will the memory
allocated to the BSTR be freed by GC or do I need to take care of
clearing off the Allocated memory?

Regards
Pawan Arya
Re: Will SysAllocString allocation be GC'ed Peggy
8/29/2006 4:17:16 PM
[quoted text, click to view]

Hi Mattias

Here's the declaration and how it is used in the C# code.

//*******DECLARATION and method IMPLEMENTATION**********//

HRESULT GetValue([in] BSTR bstrName, [out,retval] BSTR* pbstrValue);

STDMETHODIMP MyNativeClass::GetValue ( BSTR bstrName, BSTR* pbstrValue)
{
std::wstring strValue = GetValue( std::wstring( CW2W(bstrName) ),
true );
*pbstrValue = ::SysAllocString( strValue.c_str() );
return S_OK; }


//*******USAGE in C# code**********//

if (objNative.GetValue( "_Source" ) == string.Empty)
OR
m_SomeVariable.AssignVal( objNative.GetValue( "_Source" ) )

Now, will the String onject be collected by GC.

Regards,
Pawan Arya
Re: Will SysAllocString allocation be GC'ed Willy Denoyette [MVP]
8/29/2006 9:05:37 PM

[quoted text, click to view]
| Hi
|
| I have an unmanaged dll which returns a BSTR* allocated using a
| SysAllocString on the unmanaged code.
|
| Now when this BSTR is returned to the Managed world, will the memory
| allocated to the BSTR be freed by GC or do I need to take care of
| clearing off the Allocated memory?
|
| Regards
| Pawan Arya
|

Unmanaged resources aren't freed by the GC, it's your responsability to free
the BSTR*.

Willy.

Re: Will SysAllocString allocation be GC'ed Mattias Sjögren
8/29/2006 10:15:14 PM

[quoted text, click to view]

The CLR will free the BSTR during the marshaling process if the
function has been declared correctly.


Mattias

--
Mattias Sjögren [C# MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Re: Will SysAllocString allocation be GC'ed TDC
8/30/2006 5:29:40 AM
Well, you didn't actually show your C# p/invoke declaration (assuming
you don't have an interop assembly), but it looks *highly* likely from
your C# usage that the BSTR will get marshalled correctly (copied into
managed memory and then freed).

Tom

[quoted text, click to view]
AddThis Social Bookmark Button