相关疑难解决方法(0)

如何将F#委托传递给期望函数指针的P/Invoke方法?

我正在尝试在F#应用程序中使用P/Invoke设置一个低级键盘钩子.Win32函数SetWindowsHookEx接受HOOKPROC第二个参数,我将其表示为委托(int * IntPtr * IntPtr) -> IntPtr,类似于在C#中处理它的方式.在调用方法时,我得到一个MarshalDirectiveException声明,委托参数无法封送,因为

通用类型无法编组

我不确定如何涉及泛型,因为具体指定了所有类型.任何人都可以对此有所了解吗?代码如下.

编辑

这可能与F#编译器处理类型签名的方式有关 - Reflector指示委托LowLevelKeyboardProc实现为接受一个类型的参数的方法Tuple<int, IntPtr, IntPtr>- 并且将存在不可编组的泛型类型.有没有办法解决这个问题,或者F#函数是不是能够被编组到本机函数指针?

let WH_KEYBOARD_LL = 13

type LowLevelKeyboardProc = delegate of (int * IntPtr * IntPtr) -> IntPtr

[<DllImport("user32.dll")>]
extern IntPtr SetWindowsHookEx(int idhook, LowLevelKeyboardProc proc, IntPtr hMod, UInt32 threadId)

[<DllImport("kernel32.dll")>]
extern IntPtr GetModuleHandle(string lpModuleName)

let SetHook (proc: LowLevelKeyboardProc) =
    use curProc = Process.GetCurrentProcess ()
    use curMod = curProc.MainModule

    SetWindowsHookEx(WH_KEYBOARD_LL, proc, GetModuleHandle(curMod.ModuleName), 0u)
Run Code Online (Sandbox Code Playgroud)

pinvoke winapi f# delegates

9
推荐指数
1
解决办法
1293
查看次数

标签 统计

delegates ×1

f# ×1

pinvoke ×1

winapi ×1