我试图从F#调用EnumWindows并得到以下异常:
System.Runtime.InteropServices.MarshalDirectiveException: Cannot marshal 'parameter #1': Generic types cannot be marshaled.
Run Code Online (Sandbox Code Playgroud)
我使用的代码:
module Win32 =
open System
open System.Runtime.InteropServices
type EnumWindowsProc = delegate of (IntPtr * IntPtr) -> bool
[<DllImport("user32.dll")>]
extern bool EnumWindows(EnumWindowsProc callback, IntPtr lParam)
let EnumTopWindows() =
let callback = new EnumWindowsProc(fun (hwnd, lparam) -> true)
EnumWindows(callback, IntPtr.Zero)
module Test =
printfn "%A" (Win32.EnumTopWindows())
Run Code Online (Sandbox Code Playgroud)
这有点微妙,但是当您在委托定义中使用括号时,您明确告诉编译器创建一个使用元组的委托 - 然后互操作失败,因为它无法处理元组.如果没有括号,则委托创建为具有两个参数的普通.NET委托:
type EnumWindowsProc = delegate of IntPtr * IntPtr -> bool
Run Code Online (Sandbox Code Playgroud)
然后你还必须改变你的使用方式(因为它现在被视为双参数函数):
let EnumTopWindows() =
let callback = new EnumWindowsProc(fun hwnd lparam -> true)
EnumWindows(callback, IntPtr.Zero)
Run Code Online (Sandbox Code Playgroud)