C#中指標*的使用(unsafe關鍵字與fixed 語句)

來源:互聯網
上載者:User
unsafe 關鍵字表示不安全上下文,該上下文是任何涉及指標的操作所必需的。有關更多資訊,請參見 不安全的程式碼和指標(C# 編程指南)。

可以在類型或成員的聲明中使用 unsafe 修飾符。因此,類型或成員的整個本文範圍均被視為不安全上下文。例如,以下是用 unsafe 修飾符聲明的方法:  

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

不安全內容相關的範圍從參數列表擴充到方法的結尾,因此指標在以下參數列表中也可以使用:

 

 
[csharp] view plain copy unsafe static void FastCopy ( byte* ps, byte* pd, int count ) {...}   

還可以使用不安全塊從而能夠使用該塊內的不安全的程式碼。例如:  

 
[csharp] view plain copy unsafe   {       // Unsafe context: can use pointers here.   }   

若要編譯不安全的程式碼,必須指定 /unsafe 編譯器選項。無法通過公用語言運行庫驗證不安全的程式碼。 樣本  

 
[csharp] view plain copy // cs_unsafe_keyword.cs   // compile with: /unsafe   using System;   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);      }   }   
輸出 
25 
 
 
fixed 語句禁止記憶體回收行程重定位可移動的變數。fixed 語句只能出現在不安全的上下文中。Fixed 還可用於建立固定大小的緩衝區。 
 

fixed 語句設定指向託管變數的指標並在 statement 執行期間“釘住”該變數。如果沒有 fixed 語句,則指向可移動託管變數的指標的作用很小,因為記憶體回收可能不可預知地重定位變數。C# 編譯器只允許在 fixed 語句中分配指向託管變數的指標。

 
[csharp] view plain copy // assume class Point { public int x, y; }   // pt is a managed variable, subject to garbage collection.   Point pt = new Point();   // Using fixed allows the address of pt members to be &nb

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.