将C#委托转换为f#

时间:2013-12-19 20:29:56

标签: f# delegates c#-to-f#

如何将委托转换为F#?

代表:

delegate IntPtr HookProc(int code, IntPtr wParam, IntPtr lParam);

被修改

我正在做的是使用F#中的c#使用托管API执行低级键盘挂钩。

代码:

[<DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)>]
extern bool UnhookWindowsHookEx(System.IntPtr hhk);

[<DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)>]
extern System.IntPtr CallNextHookEx(System.IntPtr hhk, int nCode,System.IntPtr wParam, System.IntPtr lParam);

[<DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)>]
extern System.IntPtr GetModuleHandle(string lpModuleName);

[<DllImport("user32.dll")>]
extern System.IntPtr SetWindowsHookEx(int code, HookProc func, System.IntPtr hInstance, int threadID);

代表:

type HookProc = delegate of (int * nativeint * nativeint) -> nativeint

功能

let HookCallback(nCode:int,wParam:System.IntPtr,lParam:System.IntPtr) = 
                    let t = (int)wParam
                    if  t = WM_KEYUP then 
                         let vkCode:int = Marshal.ReadInt32(lParam)
                         printfn "%A The Pressed key code is : "  vkCode
                    CallNextHookEx(_hookID, nCode, wParam, lParam)



let HookProcF = new HookProc(HookCallback)
let SetHook() = 
                let curProcess = Process.GetCurrentProcess()
                let curModule = curProcess.MainModule
                let t =0
                let h =  GetModuleHandle(curModule.ModuleName)
                SetWindowsHookEx(WH_KEYBOARD_LL, HookProcF, h, t);



let HookMoniter() = 
        let _hookID = SetHook()
        UnhookWindowsHookEx(_hookID);

2 个答案:

答案 0 :(得分:3)

尝试以下

type HookProc = delegate of int * nativeint * nativeint -> nativeint

请注意,nativeint只是IntPtr

的F#名称

答案 1 :(得分:0)

你的意思是委托用F#调用C#函数吗?

请参阅以下内容:

Using c# delegates with f# functions

http://msdn.microsoft.com/en-us/library/dd233206.aspx