I tried to find out how pinned pointers defined with fixed
keyword work. My idea was that internally GCHandle.Alloc(object, GCHandleType.Pinned)
was used for that. But when I looked into the IL generated for the following C# code:
unsafe static void f1()
{
var arr = new MyObject[10];
fixed(MyObject * aptr = &arr[0])
{
Console.WriteLine(*aptr);
}
}
I couldn't find any traces of GCHandle
.
The only hint I saw that the pinned pointer was used in the method was the following IL declaration:
.locals init ([0] valuetype TestPointerPinning.MyObject[] arr,
[1] valuetype TestPointerPinning.MyObject& pinned aptr)
So the pointer was declared as pinned, and that did not require any additional methods calls, to pin it.
My questions are
- Is there any difference between using pinned pointers in the declaration and pinning the pointer by using
GCHandle
class? - Is there any way to declare a pinned pointer in C# without using
fixed
keyword? I need this to pin a bunch of pointers within a loop and there's no way I can do this using fixed keyword.