"关闭不能捕获可变变量"给了我一个糟糕的一天

lob*_*ism 3 f#

我正在使用一个externDLL,它有一堆返回ReturnCode枚举的例程,所以我编写了以下帮助函数来记录所有错误:

let mutable LastError = ReturnCode.OK
let mutable LastReturnCode = ReturnCode.OK
let mutable TotalErrors = 0

let Run (call: unit -> ReturnCode) =
  LastReturnCode <- call()
  if LastReturnCode <> ReturnCode.OK then
    LastError <- LastReturnCode
    TotalErrors <- TotalErrors + 1
Run Code Online (Sandbox Code Playgroud)

很棒,除了一些DLL的函数有out参数.所以现在我做的事情就像

let CreateEvfImageRef (streamHandle: int) =
  let mutable evfImageHandle = 0
  Run (fun () -> Extern.EdsCreateEvfImageRef (streamHandle, &evfImageHandle))
  evfImageHandle
Run Code Online (Sandbox Code Playgroud)

编译器给我一个"可变变量无法通过闭包捕获"的错误.除了在任何Run地方进行内容之外我还能做些什么吗?这在C#中运行良好.

(下面的extern声明示例)

[<DllImport(EDSDKPath)>]
extern ReturnCode EdsCreateEvfImageRef(int inStreamHandle, [<Out>] int& outEvfImageHandle);
Run Code Online (Sandbox Code Playgroud)

Tom*_*cek 6

您仍然可以使用该ref类型,但&在传递对函数的引用时不需要编写符号 - 编译器将自动执行此操作:

let CreateEvfImageRef (streamHandle: int) =
  let mutable evfImageHandle = ref 0
  Run (fun () -> Extern.EdsCreateEvfImageRef (streamHandle, evfImageHandle))
  !evfImageHandle
Run Code Online (Sandbox Code Playgroud)

  • *类型不匹配.期望一个byref <int> ref但给出一个int ref类型'byref <int>'与'int'类型不匹配* (2认同)