21.9 Unsafe Code Using Pointers

 <  Day Day Up  >  

You want to use unsafe code, such as code that uses pointers, in a C# program.


Technique

Writing unsafe code is relatively simple: You just need to ensure that the relevant code is contained in an unsafe block:

 
 unsafe {        // unsafe code goes here } 

If you prefer, you can mark an entire method as unsafe:

 
 static unsafe void DoSomethingUnsafe() {         // you can put unsafe code in this method without using unsafe blocks } 

Or for that matter, you can mark an entire class:

 
 unsafe class MyUnsafeClass {         // all methods in this class can contain unsafe code } 

You also need to ensure that the compiler is set to compile unsafe code. At the command line, you pass the /unsafe flag:

 
 csc /unsafe MyTest.cs 

If you are using Visual Studio.NET, you need to set the project properties to allow unsafe code. This setting automatically passes the correct flag to the compiler.

You are now set up to write to whatever unsafe code you want. For example, you can use sizeof operator:

 
 unsafe {         int x = sizeof(double);         Console.WriteLine("Double occupies {0} bytes ", x); } 

As shown in Listing 21.5, you can use a stack-allocated array to circumvent .NET array bounds checking and thereby speed up processing.

Listing 21.5 Avoiding Array Bounds Checking
 unsafe {         // allocate an int[10] array         int *pArray = stackalloc int[10];         // now do processing with *(pArray+i) to access element i, for example:         for(int i=0 ; i<10 ; i++)         {                 *(pArray+i) = 2*i;         }         // etc. } 

Comments

You should be aware that the usual provisos apply to unsafe code. Assemblies containing unsafe code might not be permitted to execute in partially trusted contexts. And of course, when using unsafe code, you risk corrupting data with pointer arithmetic bugs , so you need to take special care when debugging and checking your program logic.

 <  Day Day Up  >  


Microsoft Visual C# .Net 2003
Microsoft Visual C *. NET 2003 development skills Daquan
ISBN: 7508427505
EAN: 2147483647
Year: 2003
Pages: 440

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net