不安全代码

不安全代码不一定是危险的,它只是代码的安全性不能被CLR验证。因此,只有在完全可信的程序集内,CLR才会执行不安全的代码。如果使用不安全的代码,那么应该确保您的代码不会引入安全风险或指针错误。

不安全的关键字unsafe表示一个不安全的上下文,任何涉及指针的操作都必须添加这个关键字。

可以在一个类型、一个成员,或一个代码块声明中使用不安全的修饰符。此时,类型或成员或当前代码块的整个文本范围被认为是不安全的上下文。下面是用不安全修饰符声明例子:

unsafe static void FastCopy(byte[] src, byte[] dst, int count)  
{  
    // Unsafe context: can use pointers here.  
}  

//不安全上下文的范围从参数列表扩展到方法的末尾,因此指针也可以在参数列表中使用
unsafe static void FastCopy ( byte* ps, byte* pd, int count ) {...}  

unsafe  
{  
    // Unsafe context: can use pointers here.  
}  

class UnsafeTest
{
   // Unsafe method: takes pointer to int:
   unsafe static void SquarePtrParam(int* p)
   {
      *p *= *p;
   }

   unsafe static void Main()
   {
      int i = 5;
      // Unsafe method: uses address-of operator (&):
      SquarePtrParam(&i);
      Console.WriteLine(i);
   }
}

参考链接:

https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/unsafe

https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/unsafe-code-pointers/index

猜你喜欢

转载自www.cnblogs.com/bibi-feiniaoyuan/p/9166043.html