Monday, 5 March 2018

032 C# Unsafe Code

Unsafe code :
What is unsafe code ?
                    When we are writing pointer in a program, the code became  unsafe code. Generally. Net Framework code execute under the common language run time of CLR. Security, error, problem, performance is managed by CLR . But in unsafe code, CLR have not fully controlled over it .Code run beyond controlled of CRL.Unsafe code also termed as unmanaged code.

       There are two type of code in.Net framework
  1.  Manage code : Manage code execute fully control under the CLR. Security / exception / error  is handled by CLR.
  2.  Unmanaged code :Unmanaged code  have not control or partially control by CLR.Unmanaged code directly execute on CPU. Developer have extra burden to check security / error  for the unmanaged code as unmanaged is code bypass the security checking of CLR. Unmanaged code also can be used  when we are using memory mapping device . Unmanaged code increase the performance of a program  as manage could over head is not there.              
     


Unmanaged code or unsafe code  not run normally in .Net Framework. To run and manage code program you need to change project properties.

Project property ->build-> allow unsafe code 

                                      To use unsafe code, you need to tell compiler that you are using an unsafe code. The keyword unsafe  is used. The unsafe code block  maybe implemented in the whole program all partial where you are using the unsafe code only.

                         An unsafe code  runs under the on unsafe code block. Here is the example of unsafe program.

Example 1
       using System;
       using System.Threading;
       internal unsafe class Program
       {
                    private static void Main()
                        {
                            int* arr;
                        }
        }

It is not necessary to make the whole program under the unsafe block. It is also possible to write unsafe code under a unsafe block only. Here is the example of the same.

Example 1
         using System;
         using System.Threading;
          class Program
         {
                      private static void Main()
                     {
                     }
                     unsafe void GetFees()
                     {
                          int* arr;
                     }
           }
 Pointer:
               A pointer is a variable which content  memory address of another  variable. Pointer are used to store dynamically allocated block of memory address. A variable is declared and it has a memory address. Another variable hold the address of first variable is pointer. Pointer symbol is  *.

             To declare a pointer type variable, fast type written, then pointer notation(*) is written, then variable name is written. Appointed as a reference type
 
Example 1 
using System;
using System.Threading;
class Program
{
         unsafe void GetFees()
        {
           int* var1;
           bool* var2;
          char* var3;
          float* var4;
          decimal* var5;
          }
}
 
If you want to declare multiple pointer of same type, type name pointer symbol(*) and variable name separated by, is used.

Example 1
using System;
using System.Threading;
class Program
{
        unsafe void GetFees()
        {
          int* val1, val2, val3, val4, val5;
          bool* bool1, bool2, bool3, bool4, bool5;
         float* flt1, flt2, flt3, flt4, flt5;
       }
}
 
Following are the type ,pointer can be declared.
  •  sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal and bool.
  • User-defined structure
  • Enum types

* and &:
Two operators are used with pointers: * and &. The & is a unary operator that returns the memory address of its operand.   This address is the location of the variable in the computer’s internal memory. & can be termed as “the address of”

Example 1

using System;
using System.Threading;
class Program
      {
              private static void Main()
              {
        }
              unsafe void GetFees()
              {
                 int* val1; int val2 = 100; val1 = &val2;
              }
}

using fixed:
Fixed modifier prevent garbage collection to move the object. Pointer do not know about the garbage collection. If a garbage collection move the object, the pointer will  point to the wrong object. Fixed modifier is used on pointer  for this purpose. Here is the example of fixed.

Example 1
using System;
using System.Threading;

class Program
{
       private static void Main()
        {
        }
         unsafe void GetFees()
         {
              student obj = new student();
              fixed (int* p = &obj.a)
              {
              *p = 1;
             }
         }
}
class student
{
    public int a;
}
Structure Pointer : In the previous, you came to know that a pointer can be worked on structures also . Here is the example of the same.Structure is not reference type. Structure member can be access by  pointer and dot(.) operator.


using System;
using System.Threading;
class Program
     {
           unsafe private static void Main()
            {
            //Structure object created
            Student obj = new Student();
            //pointer declared and assigned to the object
           Student* pnt;
           pnt = &obj;
          //Struchture Value Assigned
          pnt->x = 15.96;
         pnt->y = 20.89;
         double result=obj.GetFees();
        Console.WriteLine(result);
        Console.ReadKey();
      }
}
struct Student
{
      public double x; public double y;
     public double GetFees()
     {
        return (x*y);
    }
}




Pointer Mathematics :There are only four arithmetic operators that can be used on pointers: ++, – –, +, and –.
 
using System;
using System.Threading;
class Student
{
        unsafe private static void Main()
     {
            int xVal = 5;
           int* val1;
           val1 = &xVal;
           Console.WriteLine("Value of xVal"+*val1);

          //Adding 9 with 5=14
           *val1 += 9;
          Console.WriteLine("Adding 9 with 5=" + *val1);
 
     //Adding Val1 with Val2
        int yVal = 10;
       int* val2;
       val2 = &yVal;
       *val2 = *val2 + *val1;

       Console.WriteLine("Adding Val1 with Val2=" + *val2);
      Console.ReadKey();
    }
}

Pointer Array :A pointer works on array also , you can read write array member through pointer.

using System;
using System.Threading;
class Student
{
          unsafe private static void Main()
           {
        int[] xArr = new int[5] { 1, 2, 3, 4, 5 };
              Console.WriteLine("---------------Start Reading----------------");
              //Reading a array
              fixed (int* p = xArr)
              {
                    for (int l = 0; l < xArr.Length; l++)
                    {
                       Console.WriteLine(*(p + l));
                   }
            }
             Console.WriteLine("---------------Start Writing----------------");

  
           //Writing a array
               fixed (int* p = xArr)
               {
                 for (int l = 0; l < xArr.Length; l++)
                {
                    *(p + l) = *(p + l)*2;
                    Console.WriteLine(*(p + l));
          }
             }
           Console.ReadKey();
     }
}

Passing Poniter to a Method :
A pointer can be passed to a method. When a pointer pass to the method, the address of the variable all actual pass  through  the method.
using System;
namespace UnsafeCodeApplication
{
    class Student
   {
        public unsafe void Getfees(int* param1, int* param2)
         {
            Console.WriteLine("param1 value is :"+*param1);
           Console.WriteLine("param2 value is :"+*param2);
       }
       public unsafe static void Main()
      {
        Student obj = new Student();
        int var1 = 5;
        int var2 = 6;
        int* x = &var1;
        int* y = &var2;
        obj.Getfees(x, y);
        Console.ReadKey();
       }
}

Accessing Array Element using pointer :
class Student
{
          unsafe private static void Main()
           {
        int[] xArr = new int[5] { 1, 2, 3, 4, 5 };
              Console.WriteLine("---------------Start Reading----------------");
              //Reading a array
              fixed (int* p = xArr)
              {
                    for (int l = 0; l < xArr.Length; l++)
                    {
                       Console.WriteLine(*(p + l));
                   }
            }
             Console.WriteLine("---------------Start Writing----------------");
  
           //Writing a array
               fixed (int* p = xArr)
               {
                 for (int l = 0; l < xArr.Length; l++)
                {
                    *(p + l) = *(p + l)*2;
                    Console.WriteLine(*(p + l));
          }
             }
           Console.ReadKey();
     }
}

No comments:

Post a Comment

বাঙালির বেড়ানো সেরা চারটি ঠিকানা

  বাঙালি মানে ঘোড়া পাগল | দু একদিন ছুটি পেলো মানে বাঙালি চলল ঘুরতে | সে সমুদ্রই হোক , পাহাড়ি হোক বা নদী হোক। বাঙালির ...