如何解决如何将F#委托传递给需要函数指针的P / Invoke方法?
| 我正在尝试在F#应用程序中使用P / Invoke设置低级键盘挂钩。 Win32函数SetWindowsHookEx
的第二个参数为HOOKPROC
,我将其表示为(int * IntPtr * IntPtr) -> IntPtr
的委托,类似于C#中的处理方式。当调用该方法时,我得到一个“ 3”字样,表示不能对委托参数进行封送处理,因为
通用类型无法封送
由于所有类型都已具体指定,因此我不确定如何使用泛型。谁能对此有所启发?代码如下。
编辑
这可能与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)
解决方法
您的
LowLevelKeyboardProc
定义错误。从
type LowLevelKeyboardProc = delegate of (int * IntPtr * IntPtr) -> IntPtr
至
type LowLevelKeyboardProc = delegate of int * IntPtr * IntPtr -> IntPtr
甚至更好
type LowLevelKeyboardProc = delegate of int * nativeint * nativeint -> nativeint
甚至更好
[<StructLayout(LayoutKind.Sequential)>]
type KBDLLHOOKSTRUCT =
val vkCode : uint32
val scanCode : uint32
val flags : uint32
val time : uint32
val dwExtraInfo : nativeint
type LowLevelKeyboardProc =
delegate of int * nativeint * KBDLLHOOKSTRUCT -> nativeint
在以上所有情况下,ѭ12都将使用咖喱形式而不是元组形式。
还要注意,您应该在文档中说在失败时调用ѭ15的所有extern
功能中添加ѭ13((GetModuleHandle
,SetWindowsHookEx
和UnhookWindowsHookEx
就是这种情况)。这样一来,如果发生任何故障(您应该检查返回值...),您可以简单地提出Win32Exception
或致电Marshal.GetLastWin32Error
以获得适当的诊断。
编辑:为了清楚起见,这是我在本地成功测试的所有P / Invoke签名:
[<Literal>]
let WH_KEYBOARD_LL = 13
[<StructLayout(LayoutKind.Sequential)>]
type KBDLLHOOKSTRUCT =
val vkCode : uint32
val scanCode : uint32
val flags : uint32
val time : uint32
val dwExtraInfo : nativeint
type LowLevelKeyboardProc = delegate of int * nativeint * KBDLLHOOKSTRUCT -> nativeint
[<DllImport(\"kernel32.dll\")>]
extern uint32 GetCurrentThreadId()
[<DllImport(\"kernel32.dll\",SetLastError = true)>]
extern nativeint GetModuleHandle(string lpModuleName)
[<DllImport(\"user32.dll\",SetLastError = true)>]
extern bool UnhookWindowsHookEx(nativeint hhk)
[<DllImport(\"user32.dll\",SetLastError = true)>]
extern nativeint SetWindowsHookEx(int idhook,LowLevelKeyboardProc proc,nativeint hMod,uint32 threadId)
另请注意,如果您更喜欢KBDLLHOOKSTRUCT
的值语义,那么这也将同样有效:
[<Struct; StructLayout(LayoutKind.Sequential)>]
type KBDLLHOOKSTRUCT =
val vkCode : uint32
val scanCode : uint32
val flags : uint32
val time : uint32
val dwExtraInfo : nativeint
type LowLevelKeyboardProc = delegate of int * nativeint * byref<KBDLLHOOKSTRUCT> -> nativeint
,您是否尝试过与此一起使用托管C ++。它可以使很多翻译变得非常无缝。然后,您将不需要P / Invoke。
编辑:我想指出一件相当重要的事情:编译器将为您做更多的类型检查。我确信您喜欢类型检查,因为您对应用程序的其余部分使用了F#(希望如此)。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。