閱讀652 返回首頁    go 阿裏雲 go 技術社區[雲棲]


C# 指針學習筆記之fixed 語句

大學的時候學過C++、C,最近工作也不是很忙,就想起看看C#中的指針,看看、回憶一下啊,指針的用法,以下學習筆記摘自msdn:fixed 語句

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

備注

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

// 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
// taken, and "pins" pt so it isn't relocated.
fixed ( int* p = &pt.x )
{
    *p = 1; 
}

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

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

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

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

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

          fixed (int* p1 = &p.x)
{
    fixed (double* p2 = &array[5])
    {
        // Do something with p1 and p2.
    }
}

執行完語句中的代碼後,任何固定變量都被解除固定並受垃圾回收的製約。因此,不要指向 fixed 語句之外的那些變量。

Note注意

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

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

示例
// statements_fixed.cs
// compile with: /unsafe
using System;

class Point
{ 
    public int x, y; 
}

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

    unsafe static void Main() 
    {
        Point pt = new Point();
        pt.x = 5;
        pt.y = 6;
        // Pin pt in place:
        fixed (int* p = &pt.x) 
        {
            SquarePtrParam (p);
        }
        // pt now unpinned
        Console.WriteLine ("{0} {1}", pt.x, pt.y);
    }
}

輸出

25 6

最後更新:2017-04-03 05:40:17

  上一篇:go Spark 1.0 開發環境構建:maven/sbt/idea
  下一篇:go 軟件工程學習之初