How to pass a function for parameter using VB6?

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...


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...

Tags:

Function

Vb6