F # Access to inherited field type

Given that I have a base type that is defined as follows:

[<AbstractClass>]
type HookBase(hookType: HookId, threadId: int) =
    let mutable hHook = IntPtr.Zero
    ...

    member this.SetHook() =
        // Set the hook using SetWindowsHookEx(...)
        ...
        hHook <- hhk

    member this.Unhook() =
        // Remove the hook
        hHook <- IntPtr.Zero

and derived type:

type ForegroundIdleHook(thread: uint32) as this =
    inherit HookBase(HookId.WH_FOREGROUNDIDLE, int thread)

    let hookCallback nCode wParam lParam =
        ...
        CallNextHookEx((* here has to be the hook handle *), nCode, wParam, lParam)

    ...

Since I do not want to have a code SetHook()and Unhook()each (in the end there will be 15 types of hooks), I thought about using the base type. But F # does not support members protected, now I have a problem getting hHookin derived types and setting a callback in a base type.

I thought about using CallerMemberNameAttribute and a predefined method for this:

// Base type
member this.SetCallback(callback: HookProc, [<CallerMemberName>] ?name: string) =
    ...

member this.GetHHook([<CallerMemberName>] ?name: string) =
    ...

// Derived type
do
    this.SetCallback(this.Proc)

member private this.Proc = HookProc(hookCallback)

SetCallback , , , GetHHook, " .

, - , , , , . , , F #, . ( - ?)

hook , , 15 ?

: CallerMemberName F #, , , .

+4
1

? CallNextHookEx?

, SetCallback IntPtr -> HookProc:

// Base type
member this.SetCallback(makeCallback: IntPtr -> HookProc) = 
   let callback = makeCallback hHook
   // do whatever you're supposed to do with the callback

// Derived type 
let hookCallback handle nCode wParam lParam =
    ...
    CallNextHookEx(handle, nCode, wParam, lParam)

do this.SetCallback(fun handle -> HookProc(hookCallback handle))

, , , , API Hooks, .

0

Source: https://habr.com/ru/post/1606402/


All Articles