共用方式為


fixed 關鍵詞

fixed關鍵詞可讓您將本機釘選到堆疊,以防止在垃圾收集期間進行收集或移動。 它用於低階程序設計案例。

語法

use ptr = fixed expression

備註

這會擴充表達式的語法,以允許擷取指標並將它系結至無法在垃圾收集期間收集或移動的名稱。

表達式中的指標是透過 關鍵詞固定的 fixed ,並透過 use 關鍵詞系結至標識符。 其語意類似於透過 use 關鍵詞進行資源管理。 指標在範圍中時已修正,而且一旦超出範圍,就不會再修正它。 fixed 不能在系結的內容 use 之外使用。 您必須使用 use將指標系結至名稱。

使用 fixed 必須在函式或方法的表達式內發生。 它不能用於腳本層級或模組層級範圍。

如同所有指標程序代碼,這是不安全的功能,而且會在使用時發出警告。

範例

open Microsoft.FSharp.NativeInterop

type Point = { mutable X: int; mutable Y: int}

let squareWithPointer (p: nativeptr<int>) =
    // Dereference the pointer at the 0th address.
    let mutable value = NativePtr.get p 0

    // Perform some work
    value <- value * value

    // Set the value in the pointer at the 0th address.
    NativePtr.set p 0 value

let pnt = { X = 1; Y = 2 }
printfn $"pnt before - X: %d{pnt.X} Y: %d{pnt.Y}" // prints 1 and 2

// Note that the use of 'fixed' is inside a function.
// You cannot fix a pointer at a script-level or module-level scope.
let doPointerWork() =
    use ptr = fixed &pnt.Y

    // Square the Y value
    squareWithPointer ptr
    printfn $"pnt after - X: %d{pnt.X} Y: %d{pnt.Y}" // prints 1 and 4

doPointerWork()

另請參閱