VB6的函数指针传递

时间:2022-03-31 23:15:29
Option Explicit

Private Declare Function CallWindowProc Lib "user32" Alias "CallWindowProcA" (ByVal lpPrevWndFunc As Long, ByVal hwnd As Long, ByVal msg As Long, ByVal wParam As Long, ByVal lParam As Long) As Long

Public Type MySubParams
    ID As Long
    Name As String
End Type

Sub MySub1(p As MySubParams, a As Long, b As Long, c As Long)
    Debug.Print VarPtr(p)
    MsgBox "MySub1 " & p.ID & " " & p.Name
End Sub

Sub MySub2(p As MySubParams, a As Long, b As Long, c As Long)
    Debug.Print VarPtr(p)
    MsgBox "MySub2 " & p.ID & " " & p.Name
End Sub

Function CallSub(address As Long, params As Long)
    CallSub = CallWindowProc(address, params, 0&, 0&, 0&)
End Function

Sub Start()
    Dim a As Long
    Dim p As MySubParams
    p.ID = 1
    p.Name = "Test1"
    Debug.Print VarPtr(p)
    Debug.Print CallSub(AddressOf MySub1, VarPtr(p))
    p.ID = 2
    p.Name = "Test2"
    Debug.Print CallSub(AddressOf MySub2, VarPtr(p))
End Sub