Tuesday, April 22, 2008

Pointers in c#

Sometimes people get confused when they are asked "Can we use pointers in C#?", they retorthow it can be? C# is a managed language and we can only write managed code in C# whereas pointers are unmanaged. But they are wrong... you can use pointers in C# with some extra care.

Let me first clear what is managed and unmanaged code?
Managed code is executed under the control of Common Language Runtime (CRL) and takes advantage of services provided by CLR like garbage collection(Automatic memory allocation and de-allocation), code level security,CLS etc. Whereas unmanaged code does not execute under full control of CLR so it can create some problem therefore its also called unsafe.

But CLR allows programmer to write unmanaged code along with managed code using a keyword "unsafe".you can use this keyword for any class, method or code block that contains unmanaged code.Like...

unsafe class Class1 {}

static unsafe void Method1( int* ptr, int len{...}

int* ptr;
int i = 1;
ptr = &i;
System.Console.WriteLine("Value of i is: " + *ptr);

To compile unmanaged code along with managed code you have to set "allow unsafe code" option in the build tab of the project properties window as true.

One more thing to remember when using pointers...

Because GC cleans up memory automatically, it can change the location of an object in the memory during cleaning. If that happens it may be the chance that your pointer will point to wrong location in the memory. This scenario is very difficult to debug as your program will compile sucessfully but will not give desired result.

So, to avoid such situation C# provide a keyword "Fixed" that informs CLR not to change the location of an object referenced by the pointer. Like...

// col is a managed variable.
Colour col = new Colour();
// use fixed to get address of col.R in the pointer
fixed ( int* ptr = &col.R)
*ptr = 255;

No comments: