Tuesday, 29 September 2015

Working with pointers And addresses in c# /.Net


These points needs to be remember.

1. As pointers are not safe from memory point of view. So they are categories as unsafe/unmanaged code.

2. If you want some work having pointer you must have unsafe keyword with function declaration.

       static unsafe void Check() {}

3. Unsafe code is handled by OS directly not by CLR.

4. Unmanaged object's address can be accessible through it.

An example having string,int points use

static unsafe void Check()
        {
            string s = "saurabh";
            string s1 = "saurabh";
            int x = 10;
            int y = 10;

            fixed (char* pointer = s1)
            {
                Console.WriteLine("dsds");
            }

            fixed (char* pointer1 = s)
            {
                Console.WriteLine("dsds");
            }

            //void* add1 = &s;
            //void* add2 = &y;

            //Console.WriteLine(x, (int)add1, *add1);
        }
    }


Note : To build unmanaged code from c sharp or vs you have to allow build unsafe code from project property build tag.