Search This Blog

Friday, June 21, 2013

Using Pointers in C#

<<...unsafe keyword:
Typically when we write code in C# by default it is what's known as safe code. Unsafe code allows you to manipulate memory directly, in the normal world of C# and the .NET Framework, this is seen as potentially dangerous, and as such you have to mark your code as unsafe. Using unsafe code, you are loosing garbage collection and whilst directly accessing memory, you have the possibility of accessing memory that you didn't want to and causing untold problems with your application. Unsafe code can only be used within a fully trusted assembly....>>

Pointers in C#

<<..Enter the fixed keyword. When used for a block of statements, it tells the CLR that the object in question cannot be relocated, and thus, it ends up pinning the object. Thus, when pointers are used in C#, the fixed keyword is used pretty often to prevent invalid pointers at runtime.
 ...>>

using System;
class CData
{
    public int x;
}

class CProgram
{
    unsafe static void SetVal(int *pInt)
    {
        *pInt=1979;
    }
    
    public unsafe static void Main()
    {
        CData d = new CData();
        
        Console.WriteLine("Previous value: {0}", d.x);
        
        fixed(int *p=&d.x)
        {
            SetVal(p);
        }
        
        Console.WriteLine("New value: {0}", d.x);
    }
}


Unsafe programming in C#


No comments:

Post a Comment

Blog Archive

About Me

An seasoned developer, architect and with some Team Leading exposure, offering full project life cycle experiences within multi cultural, multi National environments and within differing business streams and all primarily on a .Net platform.