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

unsafe 關鍵字表示不安全上下文,該上下文是任何涉及指針的操作所必需的。有關更多信息,請參見不安全代碼和指針(C# 編程指南)

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

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

不安全上下文的範圍從參數列表擴展到方法的結尾,因此指針在以下參數列表中也可以使用:

  1. unsafe static void FastCopy ( byte* ps, byte* pd, int count ) {...}

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

  1. unsafe
  2. {
  3. // Unsafe context: can use pointers here.
  4. }

若要編譯不安全代碼,必須指定 /unsafe 編譯器選項。無法通過公共語言運行庫驗證不安全代碼。

  1. // cs_unsafe_keyword.cs
  2. // compile with: /unsafe
  3. using System;
  4. class UnsafeTest
  5. {
  6. // Unsafe method: takes pointer to int:
  7. unsafe static void SquarePtrParam(int* p)
  8. {
  9. *p *= *p;
  10. }
  11. unsafe static void Main()
  12. {
  13. int i = 5;
  14. // Unsafe method: uses address-of operator (&):
  15. SquarePtrParam(&i);
  16. Console.WriteLine(i);
  17. }
  18. }

輸出

25

 
 
fixed 語句禁止垃圾回收器重定位可移動的變量。fixed 語句只能出現在不安全的上下文中。Fixed 還可用於創建固定大小的緩衝區

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

  1. // assume class Point { public int x, y; }
  2. // pt is a managed variable, subject to garbage collection.
  3. Point pt = new Point();
  4. // Using fixed allows the address of pt members to be
  5. // taken, and "pins" pt so it isn't relocated.
  6. fixed ( int* p = &pt.x )
  7. {
  8. *p = 1;
  9. }

可以用數組或字符串的地址初始化指針:

  1. fixed (int* p = arr) ... // equivalent to p = &arr[0]
  2. fixed (char* p = str) ... // equivalent to p = &str[0]

只要指針的類型相同,就可以初始化多個指針:

fixed (byte* ps = srcarray, pd = dstarray) {...}

要初始化不同類型的指針,只需嵌套 fixed 語句:

  1. <pre class="csharp" name="code">fixed (int* p1 = &p.x)
  2. {
  3. fixed (double* p2 = &array[5])
  4. {
  5. // Do something with p1 and p2.
  6. }
  7. }
執行完語句中的代碼後,任何固定變量都被解除固定並受垃圾回收的制約。因此,不要指向 fixed 語句之外的那些變量。
Note注意

無法修改在 fixed 語句中初始化的指針。

在不安全模式中,可以在堆棧上分配內存。堆棧不受垃圾回收的制約,因此不需要被鎖定。有關更多信息,請參見 stackalloc


  1. // statements_fixed.cs
  2. // compile with: /unsafe
  3. using System;
  4. class Point
  5. {
  6. public int x, y;
  7. }
  8. class FixedTest
  9. {
  10. // Unsafe method: takes a pointer to an int.
  11. unsafe static void SquarePtrParam (int* p)
  12. {
  13. *p *= *p;
  14. }
  15. unsafe static void Main()
  16. {
  17. Point pt = new Point();
  18. pt.x = 5;
  19. pt.y = 6;
  20. // Pin pt in place:
  21. fixed (int* p = &pt.x)
  22. {
  23. SquarePtrParam (p);
  24. }
  25. // pt now unpinned
  26. Console.WriteLine ("{0} {1}", pt.x, pt.y);
  27. }
  28. }

輸出

25 6

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章