Joydip Kanjilal
Contributor

How to work with unsafe code in .Net

opinion
Oct 30, 20154 mins
Software Development

Take advantage of the unsafe keyword to write unmanaged code in .Net

The C# programming language doesn’t allow you to work with pointers by default. You need to use the unsafe keyword to define an unsafe context and write code that uses pointers. Unsafe code helps you write unmanaged code that wouldn’t be handled by the execution environment of the CLR. This article takes a look at how we can work with unsafe code in the managed environment of .Net.

What is unsafe code anyway?

With unsafe code, the safety of the code cannot be verified by the CLR. In other words, unsafe or unmanaged code is executed outside of the context of the CLR. Unsafe code helps you invoke native functions using pointers. Note that when writing unsafe code you should ensure the program doesn’t incur any security risks, memory faults, or so on. To write unsafe code, you should use the unsafe keyword. You define methods, types, and code blocks as unsafe using the unsafe keyword.

Pointers

A pointer is a variable that points to the address of another variable. In other words, a pointer holds the memory address of another variable or a memory location. Note that the data type of a pointer should match the data type of the variable to which it points. Hence, for a pointer to indicate an integer variable, the type of the pointer should be integer. The three operators that you would frequently make use of while working with pointers include the following:

  • *
  • &
  • ->

The following piece of code shows how you can define a pointer and make it point to the address of a variable.

int i = 100;

int *ptr = & i;

Refer to the code snippet above. In the first statement we assign the value 100 to an integer variable. In the next statement we define an integer pointer and make it point to the address of the variable using the & operator.

Here’s a snippet of code that illustrates how we can use the unsafe keyword to display the memory address of a variable.

static void Main(string[] args)

        {

          unsafe

          {

            int i = 100;

            int* ptr = &i;

            Console.WriteLine

           ("The value of i is : " + i);

            Console.WriteLine

          ("The memory address of i is : " + (int)ptr);

          }

            Console.ReadKey();

        }

Note that usage of the unsafe keyword. If you omit unsafe and compile the above code, you would see the following error.

“Pointers may only be used in an unsafe context”.

The above error message clearly states that you should write your unsafe code within an unsafe context — exactly what unsafe provides you.

Assuming you’re using Visual Studio IDE for writing and compiling your program(s) that leverage unsafe code, you should enable unsafe code for your project in the Visual Studio IDE. To do so, follow these steps:

  • Select the project and right-click on it
  • In the project properties window, click on the Build tab
  • Next, select the “Allow unsafe code” check box

Note that you can also compile your program that contains unsafe code using the csc command-line compiler as shown below:

csc /unsafe myprogram.cs

The above program when executed would display the value and also the memory address of the variable i.

You can also mark a method as unsafe via the unsafe keyword. Here’s an example that shows how you can do this:

public unsafe void Compute(int* ptr)

  {

      *ptr = (*ptr) * 10;

  }

You can now invoke the Compute function as shown below.

unsafe {

            int i = 100;

            int* ptr = &i;

            Compute(&i);

            Console.WriteLine("The value of the variable i is : " + i);

            }

When you execute the above code snippet, you would observe that the value of the variable i has been changed from 100 (its initial value) to 1,000. The Compute function accepts a pointer as an argument and multiplies the value of the variable to which the pointer points by 10. Note that *ptr refers to the content of the variable to which ptr points, which incidentally is 100. This value is multiplied by 10 — hence the result.

When working with unsafe code in a managed environment you might need to use the fixed keyword to logically place the variable in memory so that the runtime doesn’t move the variable around in memory while compacting the memory due to heap fragmentation. In essence, you can use the fixed keyword to eliminate the issues related to invalid pointers. You can also use fixed to pin an array and retrieve pointer to the data in the array.

I would discuss more on unmanaged code in my future articles here.

Joydip Kanjilal
Contributor

Joydip Kanjilal is a Microsoft Most Valuable Professional (MVP) in ASP.NET, as well as a speaker and the author of several books and articles. He received the prestigious MVP award for 2007, 2008, 2009, 2010, 2011, and 2012.

He has more than 20 years of experience in IT, with more than 16 years in Microsoft .Net and related technologies. He has been selected as MSDN Featured Developer of the Fortnight (MSDN) and as Community Credit Winner several times.

He is the author of eight books and more than 500 articles. Many of his articles have been featured at Microsoft’s Official Site on ASP.Net.

He was a speaker at the Spark IT 2010 event and at the Dr. Dobb’s Conference 2014 in Bangalore. He has also worked as a judge for the Jolt Awards at Dr. Dobb's Journal. He is a regular speaker at the SSWUG Virtual Conference, which is held twice each year.

More from this author