Monday, 14 May 2012

Using pointers in C#

Due to the implementation of CLR, using pointers in .NET is very different from C/C++, in the .NET environment you are supposed to run managed code, although you can rum unmanaged code CLR doesn’t like it very much (read this), so if a programmer wants to run some unmanaged code it must inform CLR of its intensions, this way CLR will know that it is not an error, for this just use the reserved word “unsafe” and the library System.Runtime.InteropServices. This is an example of how to access memory positions using a reference type Point:

using System;
using System.Runtime.InteropServices;

class Point 
{
 public int x, y;
 public Point(int x, int y) 
 {
  this.x=x; this.y=y;
 }
 
 public override String ToString() 
 {
  return String.Format("({0},{1})", x, y);
 }
}

class Program 
{
 unsafe private static void printAdresses(Point p1, Point p2)
 {
  // Printing Point1 addresses
  fixed(int* p1_Xpointer = &p1.x)
  {
   IntPtr addr = (IntPtr)p1_Xpointer;
   Console.WriteLine("Point1 X address:" + addr.ToString("x"));
  }
  
  fixed(int* p1_Ypointer = &p1.y)
  {
   IntPtr addr = (IntPtr)p1_Ypointer;
   Console.WriteLine("Point1 Y address:" + addr.ToString("x"));
  }
  
  // Printing Point2 addresses
  fixed(int* p2_Xpointer = &p2.x)
  {
   IntPtr addr = (IntPtr)p2_Xpointer;
   Console.WriteLine("Point2 X address:" + addr.ToString("x"));
  }
  
  fixed(int* p2_Ypointer = &p2.y)
  {
   IntPtr addr = (IntPtr)p2_Ypointer;
   Console.WriteLine("Point2 Y address:" + addr.ToString("x"));
  }
 }
 
 
 static void Main(string[] args)
 {
  // Creating two reference types of Point, p1 and p2,
  Point p1 = new Point(1, 2), p2 = new Point(3, 4);
  Console.WriteLine("Point1:{0}\nPoint2:{1}\n", p1,p2);
  printAdresses(p1, p2);
  Console.WriteLine("p1 and p2 point to diferent addresses\n");
  // pointing p2 to p1, addresses should be the same now
  p2 = p1;
  printAdresses(p1, p2);
  Console.WriteLine("p1 and p2 point to the same address, the old p2 is now gone\n");
 }
}
}

To compile this source code use "csc /unsafe FILENAME.cs"

No comments:

Post a Comment