Sponsored Ad

Tuesday, October 13, 2009

C# Fixed

The fixed statement prevents the garbage collector from relocating a movable variable. The anchored account is alone acceptable in an alarming context. Anchored can aswell be acclimated to actualize anchored admeasurement buffers.

The fixed statement sets a pointer to a managed variable and "pins" that variable during the execution of statement. Without fixed, pointers to adaptable managed variables would be of little use back debris accumulating could backpack the variables unpredictably. The C# compiler only lets you assign a pointer to a managed variable in a fixed statement.

// assume class Point { public int x, y; }
// pt is a managed variable, subject to garbage collection.
Point pt = new Point();
// Using fixed allows the address of pt members to be
// taken, and "pins" pt so it isn't relocated.
fixed ( int* p = &pt.x )
{
    *p = 1;
}

You can initialize a pointer with the address of an array or a string:

 

 

fixed (int* p = arr) ...  // equivalent to p = &arr[0]
fixed (char* p = str) ... // equivalent to p = &str[0]

To initialize pointers of different type, simply nest fixed statements:

fixed (int* p1 = &p.x)
{
    fixed (double* p2 = &array[5])
    {
        // Do something with p1 and p2.
    }
}

Example:

// statements_fixed.cs
// compile with: /unsafe
using System;

class Point
{
    public int x, y;
}

class FixedTest
{
    // Unsafe method: takes a pointer to an int.
    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);
    }
}

Output:
25 6

0 comments:

Post a Comment

Sponsored Ad

Website Update

Followers