C# Crawler
Sagiv Hadaya is crawling in C#...just for fun




 

Unsafe Coding in C#

Its a catchy title..unsafe code...but also sounds like it can risk our application!

Well, yes and no, unsafe code in C# means usage of pointers, what the CLR does behind the scenes when we use a managed code is part of it, and by stating that we have an unsafe code, we declare a function/line to be 'able' to reach memory directly.

Sounds confusing? wait, the CLR as we all know does few very important things for our application, while running (after jitted):

  • managing the memory for the objects
  • doing garbage collection at any needed time
  • performing type verification

    Our managed code is safe from those issues, and does not have to deal with them, however there are situations when you need very badly a pointer, or a direct memory access, and must use pointers.

    At this location we call on unsafe, unsafe is a declaration we place at every line of code, or at the beginning of a function, to state that it is using pointers, to simplify this long sentance:

    every line/function that make use of these operators: -> , * , & 

    must declare itself as unsafe:

    public unsafe void Set(int *p)
    {
          *p=(*p)+1;

    }

    Looks not so unsafe, but it is, the pointer is an address, which is written in the CLR global address space, we are actually using the 'memory' as we wish, and this is unsafe.

    Now, consider this: the unsafe code is running under the CLR, and the CLR for some reason needs to fragment the 'memory', by doing so, the CLR (by definition) is free to move objects around, and change thier address (who knew you will use unsafe right), so in our 3 lines of code obove *p will have a different address, and might point to a new fragmented location which CANNOT be touched...unsafe ha?

    there is a cure for that, its called 'fixed', when using the 'fixed' keyword in front of a code block, causes the CLR to pinpoint the object in reference, and not release/change its location, at least until the application ends.

    So in our example obove nothing really needs to changed, the caller on the other hand should state 'fixed' in the calling statement (and unsafe in the function, or code block) and by that will be sured that the pointer will be valid:

    class A
    {
        public int x;
    }

    class MainApp
    {
        unsafe static void Set(int *p)
        {
            *p=(*p)+1;
        }
       
        public unsafe static void Main()
        {
            A a = new A();

            A.x = 10;
              
            fixed(int *p=&A.x)
            {
                Set(p);
            }
            
         }
    }

    This is fairly self explainable isnt it?, there is a class A which holds a public integer x, our main app has a function that somehow needs an int address in order to manipulate it, so we pass it &x, which is the address of x, but note the fixed keyword that the CALLER is using, this is to prevent the CLR from manipulating our pointer at run time.


  • Click here to visit the Radio UserLand website.
    Click to see the XML version of this web page.
    Click here to send an email to the editor of this weblog.
    © Copyright 2002 Sagiv Hadaya.
    Last update: 10/11/2002; 1:51:10 AM.