I came across the following code on msdn:
unsafe static void SquarePtrParam (int* p)
{
*p *= *p;
}
unsafe static void Main()
{
Point pt = new Point();
pt.x = 5;
pt.y = 6;
// Pin pt in place:
fixed (int* p = &pt.x)
{
SquarePtrParam (p);
}
// pt now unpinned.
Console.WriteLine ("{0} {1}", pt.x, pt.y);
}
I am just wondering, we are directly accessing pointer in SquarePtrParam
function, does it inherit information that array is fixed from calling method?
Why don't we need to explicitly set it to fixed
locally in SquarePtrParam
.
I guess I could use some elaborations about this fixed
statement.
Fixed statement implement unpin memory area in the same manner as "using" statement close opened files in using(FileStream stream = new FileStream(..)) construction. Memory will be pinned until you left the fixed code block.
In the IL code it will create dummy PINNED local variable and store a pointer into it. This will not allow GC move memory area contains this pointer. After you will left fixed block it will store zero into this PINNED variable. Just like this:
So FixedDemo in IL Code:
For more information visit:
MSDN
MSDN Magazine: Garbage Collection: Automatic Memory Management in the Microsoft .NET Framework
Common language Runtime standard ECMA 335 Partition III, 1.1.4.2 Managed Pointer (type &)
No, it doesn't need that information. All it knows is that it's been passed a pointer. One way of obtaining a pointer is via the
fixed
statement, but there are other ways (e.g. by converting an IntPtr), and any such compatible pointers could also be passed toSquarePtrParam
.