27 oct 2007

unsafe keyword + Using Pointers in C#

Using Pointers in C#

Now it is time to write some program code to demonstrate the use of pointers. Consider the following code.

static void Main(string[] args)
{
    int age = 32;
    Console.WriteLine("age = {0}" , age);
}

unsafe keyword

static void Main(string[] args)
{
    unsafe
    {
        int age = 32;
        int* age_ptr;

        Console .WriteLine("age = {0}", age);

    }
}

 

Pointers to Structures:

unsafe static void Main(string[] args)

{

    Location loc;

    loc.X = 100;

    loc.Y = 100;

 

    Location* loc_ptr;

    loc_ptr = &loc;

    Console.WriteLine("X = {0}", loc_ptr->X);

 

    loc_ptr->X = 200;

    Console.WriteLine("X = {0}", loc_ptr->X);

}

 

Pointers and Classes:

For Example:

 

class PTest

{

     public PTest()

     {

     }

     public int age;

     public void DisplayAge()

     {

         Console.WriteLine("age = {0}", age);

    }

}

And some example code to create an instance of the class and then manipulate the public variable age using a pointer.

unsafe static void Main(string[] args)
{
    PTest p = new PTest();

    p.age = 32;
    p.DisplayAge();

    fixed (int* age = &p.age)
    {
        *age += 3;
    }

    p.DisplayAge();
}

 

No hay comentarios:

FeedCount

analytics

 
sfrede