固定关键字

使用 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()

另请参阅