Unsafe Keyword

Why we use pointer in C#.NET with Unsafe keyword?

Questions by praveenkumar121

Showing Answers 1 - 9 of 9 Answers

Interfacing with the underlying operating system, accessing a memory-mapped device may not be possible or practical without access to pointers. To address this need, We use unsafe code. Unsafe code is like writing a C code in C# program.

  Was this answer useful?  Yes

kvvsmbalaji

  • Jul 16th, 2010
 

As we know, the CLR is responsible for managing the execution of code compiled for the .NET platform. The code that satisfies the CLR at runtime in order to execute is reffered as Managed Code.

Unsafe Code
C# does not support pointers, we may declare certain classes and methods as "Unsafe" it is code that does not execute under the full management of the Common Language Runtime (CLR).

Given that unsafe code might cause problems,  you might ask why anyone would want to create such code.  The answer is that managed code prevents the use of pointers.

Since a pointer can point anywhere in the memory, it is possible to misuse a pointer.
It is also easy to introduce a coding error when using pointers.

This is why C# does not support pointers when creating managed code. Pointers are however, both useful and necessary for some types of programming (such as system-level utilities), and C# does allow you to create and use pointers.

All pointer operations must be marked as unsafe, since they execute outside the managed context.

The following example uses pointers to copy an array of bytes from src to dst. Compile the example with the /unsafe option.
// fastcopy.cs
// compile with: /unsafe
using System;
 
class Test
{
    // The unsafe keyword allows pointers to be used within
    // the following method:
    static unsafe void Copy(byte[] src, int srcIndex,
        byte[] dst, int dstIndex, int count)
    {
        if (src == null || srcIndex < 0 ||
            dst == null || dstIndex < 0 || count < 0)
        {
            throw new ArgumentException();
        }
        int srcLen = src.Length;
        int dstLen = dst.Length;
        if (srcLen - srcIndex < count ||
            dstLen - dstIndex < count)
        {
            throw new ArgumentException();
        }
 
 
            // The following fixed statement pins the location of
            // the src and dst objects in memory so that they will
            // not be moved by garbage collection.         
            fixed (byte* pSrc = src, pDst = dst)
            {
                  byte* ps = pSrc;
                  byte* pd = pDst;

            // Loop over the count in blocks of 4 bytes, copying an
            // integer (4 bytes) at a time:
            for (int n =0 ; n < count/4 ; n++)
            {
                *((int*)pd) = *((int*)ps);
                pd += 4;
                ps += 4;
            }
 
            // Complete the copy by moving any bytes that weren't
            // moved in blocks of 4:
            for (int n =0; n < count%4; n++)
            {
                *pd = *ps;
                pd++;
                ps++;
            }
            }
    }
 
 
    static void Main(string[] args)
    {
        byte[] a = new byte[100];
        byte[] b = new byte[100];
        for(int i=0; i<100; ++i)
           a[i] = (byte)i;
        Copy(a, 0, b, 0, 100);
        Console.WriteLine("The first 10 elements are:");
        for(int i=0; i<10; ++i)
           Console.Write(b[i] + " ");
        Console.WriteLine("n");
    }
}


Naveen.ahamed S

  Was this answer useful?  Yes

phanish

  • Jul 16th, 2010
 

In C# the value can be directly referenced to a variable, so there is no need of pointer. Use of pointer sometime crashes the application. But C# supports pointer, that means we can use pointer in C#.

The use of pointer in C# is defined as a unsafe code. So if we want to use pointer in C# the pointer must be present in the body of unsafe declaration. But pointer does not come under garbage collection.

Example:

unsafe
{
int a, *b;
a = 25;
b = &a;
Console.WriteLine("b= {0}",b);//returns b= 25
}

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions