CallBack Method?

BlitzMax Forums/BlitzMax Beginners Area/CallBack Method?

Thareh(Posted 2010) [#1]
Hi!
I'm wondering if it's possible to CallBack a method?
Couldn't get it working so I'm not sure it's implemented.


Something like this :)


Htbaa(Posted 2010) [#2]
Nope, it's not supported.


Czar Flavius(Posted 2010) [#3]
It's awkward, but you can do this.
Type MyType
    
    Field MyCallBackFunc:Int(me:MyType)
    Field num = Rand(0,100)
    
    Function TestMethod:Int(me:MyType)
        Print me.num
    End Function

End Type

Local A:MyType = New MyType
A.MyCallBackFunc = MyType.TestMethod
A.MyCallBackFunc(A)



Dreamora(Posted 2010) [#4]
or use reflection and create kind of a "delegate model"


Brucey(Posted 2010) [#5]
Well, something like what Flavius says... but I think his example isn't so clear.
Type BaseType

	Method myCallback:Int()
		DebugLog "Please Implement me!"
	End Method

	Function callback:Int(ref:BaseType)
		Return ref.myCallback()
	End Function

End Type

Type MyType Extends BaseType
    
 	Method myCallback:Int()
		Return 100
	End Method

End Type


' somewhere that calls a user-callback :

Local A:BaseType = New MyType

Print BaseType.callback(A)


This way, the "user type" only needs to implement a callback method.
I use this a lot in many places, where a 3rd-party (C++) library can make a callback into user code. It completely hides the underlying complexity (of data conversions and pointers) from the user.
For example, a typical callback would pass Byte Ptrs, which should be hidden from the exposed API :

   Function doCallback(obj:BaseType, param1:Byte Ptr, param2:Byte Ptr)
      obj.myCallback(_convertToTypeA(param1), _convertToTypeB(param2))
   End Function



As Dreamora mentions, there are many ways to do it.

My Qt event model uses some Reflection magic to build on top of a signal/slot system, which allows for a different variation of callback methods.