Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the notion behind 'Pinned GC handle'?

When we analyse memory heaps, following 4 types of GC handles we generally come across:

  1. Weak:- A weak GC handle will not prevent the instance it corresponds to from being garbage collected. Example, used by the System.WeakReference class instances.

  2. Normal:- A normal GC handle prevents the corresponding instance from being garbage collected.Example, used by the instances of strong references.

  3. RefCounted:- A reference counted GC handle is used internally by the runtime, example, when dealing with COM interfaces.

  4. Pinned:- Why do we need this kind of GC handle? Is it just for avoiding the movement of that instance in memory or is there any other notion behind this? I want to know the notion behind Pinned GC handle(with an example).

Edited for Itay's answer:- I have a non empty array-DiffCell[][] which is bound to a data grid in WPF. When I close the window on which this data grid is present, on heap I see Pinned GC handle pointing to this empty DiffCell array through object[](see snapshot). I am not using any unsafe code. I am just setting ItemsSource of data grid to null before closing that window. So my question is who does pin this array on heap and why?

alt text

like image 713
Kushal Waikar Avatar asked Jan 18 '11 10:01

Kushal Waikar


2 Answers

We need this in case we use pointers.
Imagine that you declare a pointer to a memory location and you do not pin in.
The GC sometimes move memory chunks to other places so your pointer will get invalid.

for example:

public unsafe void DoSomething(byte b)
{
   byte * bp = &b;
}

this will not compile because you didn't fix memory location that holds the byte.
In order to pin it you can use:

public unsafe void DoSomething(byte b)
{
   fixed(byte * bp = &b)
   {
        //do something
   }
}
like image 137
Itay Karo Avatar answered Sep 17 '22 21:09

Itay Karo


Dont forget GCHandle which supports pinning objects (and retrieving the address as an IntPtr). Pinning objects aren't exclusive to unsafe code (the fixed statement).

like image 25
sisve Avatar answered Sep 20 '22 21:09

sisve