Friday 29 July 2005

Unsafe clause in C#

Unsafe clause is used to point out the unsafe environments in C#. As we know, there is no pointer in C#,for the pointer is "unsafe", if a pointer points to a  unexpected location in memory, it might cause exception. If we want to use pointers in C#, we have to use them in an "unsafe " environment that CLR knows.
1).Unsafe clause could define a method, property or ctor(unstatic ctor) as unsafe.The unsafe method is from the parameters of method to the end of the method.
for example:


1static unsafe void FastCopy(byte* ps, bype* pd,int count)
2
2)  unsafe clause also could mention a unsafe clause or a clause block.like this :


unsafe 
{
unsafe clause1;
unsafe clause2;

}
However, if you have only one clause , you should also use a pair of brackets.(tested under 2002, - - ~~~OU~so old...)
an complete small test code like this:



using System;
class UnsafeTest
{
//here we could find "unsafe static"=="static unsafe",compile result is the same.
unsafe static void SquarePtrParam(int* p)
{
*p*=*p;
}

[STAThread]
public  static void Main(string[] args)
{
   
int i=5;
   
unsafe     
   
{
     SquarePtrParam(
&i);
   }

   Console.WriteLine(
"i"+i);
}

}
Here ,we could know, When you want to use a pointer(usually the type of the pointed is a  numberic value not a reference value), as a parameter in a unsafe method,you also will use a pointer as an input parameter when you use this unsafe method,so ,the invoke class should also have an unsafe clause block.

Plus: if you want to compile unsafe code under the CLR, you need to mention /unsafe to compiler directly. You can set this property in your project property page (right click the project in solution manager explore, then you will find it at the bottom of the menu.)Then, click the configuration property ,and choose "generation"-- the first subchoice.
You will find the default property of  allowing unsafe check is false .You need to set it to "True".

For further study ,I want to explore the difference between the safe method and the unsafe.That 's need knowledge of IL language. I hope I could explore after getting a book about IL.:)

Note: For my .NET IDE is a Chinese version, I don't know whether words about  the english menu are correct. Sorry~~