Does GC collect unmanaged objects pointed by a class field?

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi,

I have an unmanaged function which returns an address to an unmanaged
object. It's implemented by native C.

I call this function by p/invoke, get the pointer in C#, and store it in a
class field.
And I use this pointer to store some date in the unmanaged object.

My question is, does gc do anything with this object?

I presume that GC won't take care of it, because it's not in managed heap.
Is it true?

Thanks,
Tomoki
 
Hi,

You should implement the dispose pattern (google it). In you disposal
routine you should call whatever C function frees the unmanaged object.
 
Hi Tomoki

You are right, the GC will not free the unmanged memory. To free the memory from managed code, follow Stelrad's advice about the Dispose pattern.

-Chris


--------------------
Hi,

You should implement the dispose pattern (google it). In you disposal
routine you should call whatever C function frees the unmanaged object.


--

This posting is provided "AS IS" with no warranties, and confers no rights. Use of included script samples are subject to the terms specified at
http://www.microsoft.com/info/cpyright.htm

Note: For the benefit of the community-at-large, all responses to this message are best directed to the newsgroup/thread from which they originated.
 
Hi,

Thanks for the perfect answer, Chris and Stelrad.
My understanding is crystal clear now.

Tomoki


"Chris Lyon [MSFT]" said:
Hi Tomoki

You are right, the GC will not free the unmanged memory. To free the memory from managed code, follow Stelrad's advice about the Dispose pattern.

-Chris


--------------------
Hi,

You should implement the dispose pattern (google it). In you disposal
routine you should call whatever C function frees the unmanaged object.


--

This posting is provided "AS IS" with no warranties, and confers no rights. Use of included script samples are subject to the terms specified at
http://www.microsoft.com/info/cpyright.htm

Note: For the benefit of the community-at-large, all responses to this message are best directed to the newsgroup/thread from which they originated.
 
Back
Top