Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a function for parameter using VB6?

Tags:

function

vb6

How can I do to pass a function by parameter, later to be called in VB6? would be something like what I need, can be any of these options:

Private Sub Command1_Click()

    Call callMethod(MyPrivateFunction)
    Call callMethod(MyPublicFunction)
    Call callMethod(MyPrivateSub)
    Call callMethod(MyPublicSub)

End Sub

Private Function MyPrivateFunction()
    MsgBox "MyPrivateFunction"
End Function

Public Function MyPublicFunction()
    MsgBox "MyPublicFunction"
End Function

Private Sub MyPrivateSub()
    MsgBox "MyPrivateSub"
End Sub

Public Sub MyPublicSub()
    MsgBox "MyPublicSub"
End Sub

Public Function callMethod(ByRef func As Object)
    Call func
End Function
like image 388
andres descalzo Avatar asked Sep 29 '09 16:09

andres descalzo


2 Answers

IIRC there is an AddressOf function in VB6 to get function addresses, but you will likely have great difficulty actually using that function address from within VB6.

The SOP way to handle this is with CallByName() which allows you to, you know, call functions, etc. by their names.

finally, you can also take the high road, by using the standard OO solution to this: Instead of passing the function, write your own class that implements a special interface of your own design MyFunctionInterface. This interface has only one method FunctionToCall(..), which you can implement in different classes to call the different functions that you need. Then you pass an instance of one of these classes to your routine, that receives it as MyFunctonInterface and calls the FunctionToCall method on it. Of course that takes a whole lot of minor design changes...

like image 83
RBarryYoung Avatar answered Sep 22 '22 10:09

RBarryYoung


You can't pass a function, but you can pass an object that behaves as a function (called a "functor" sometimes). I use this all the time. If you "functor" class Implements an interface, the call will be type safe. For example:

Abstract class (Interface) IAction.cls:

Option Explicit

Public Sub Create(ByVal vInitArgs As Variant)

End Sub

Public Function exe() As Variant

End Function

Functor that displays a url in the default browser:

Option Explicit

Implements IAction
Dim m_sUrl As String

Public Sub IAction_Create(ByVal vInitArgs As Variant)
        m_sUrl = vInitArgs    
End Sub

Public Function IAction_exe() As Variant


       Call RunUrl(m_sUrl) 'this function is defined elsewhere  

Exit Function

You can now create a bunch of these classes, save them in a collection, pass them to any function or method that expects an IAction, etc...

like image 34
cfischer Avatar answered Sep 18 '22 10:09

cfischer