Function Pointers passed as parameters

BlitzMax Forums/BlitzMax Beginners Area/Function Pointers passed as parameters

Jim Teeuwen(Posted 2004) [#1]
Im having abit of trouble finding a proper way to pass a function as a parameter. Im trying to get the following code to work on the Win32 compiler.

Strict
Type TEventHandler

	Field Execute:Int( Sender:Object, Arg:Object )

	Function Create:TEventHandler( target:Int( Sender:Object, Arg:Object ) )
		Local eh:TEventHandler	= New TEventHandler
		eh.Execute		= target
		Return eh
	End Function

End Type

Type MyType

	Method New()
	End Method

	Method Test()

		'// Raise first event
		Self.OnTestStarted( Self, Null )

		'// Do some random stuff
		Local k:Int
		For k = 0 To 10
			Print( k + ". " + MemAlloced() )
			Delay( 100 )
		Next

		'// Raise second event
		Self.OnTestEnded( Self, Null )

	End Method


	'// available events
	Field TestStarted:TList	= New TList
	Field TestEnded:TList	= New TList

	'// Event Raising
	Method OnTestStarted( Sender:Object, Arg:Object )
		'// Execute all hooked 'TestStart' handlers
		Local eh:TEventHandler
		For eh:TEventHandler = EachIn Self.TestStarted
			eh.Execute( Sender, Arg )
		Next
	End Method
	Method OnTestEnded( Sender:Object, Arg:Object )
		'// Execute all hooked 'TestEnd' handlers
		Local eh:TEventHandler
		For eh:TEventHandler = EachIn Self.TestEnded
			eh.Execute( Sender, Arg )
		Next
	End Method
  

End Type

Type Demo

	Method Run()

		Local _mytype:MyType	= New MyType

		'// Hook some events!
		_mytype.TestStarted.AddLast( TEventHandler.Create( HandleTestStart ) )
		_mytype.TestEnded.AddLast( TEventHandler.Create( HandleTestEnd ) )

		'// Run it all
		_mytype.Test()

	End Method


	Method HandleTestStart( Sender:Object, Arg:Object )
		Print( "TestStart Handler fired!" )
	End Method
	Method HandleTestEnd( Sender:Object, Arg:Object )
		Print( "TestEnd Handler fired!" )
	End Method

End Type


Local d:Demo = New Demo
d.Run()


The compiler hans on the line
_mytype.TestStarted.AddLast( TEventHandler.Create( HandleTestStart ) )

It pops a message saying "Unable to convert from type 'Int( Object,Object ) to 'Int( Object,Object )'.

Is there something I overlooked here?


Michael Reitzenstein(Posted 2004) [#2]
Pointers to methods, commonly known as delegates, aren't supported in BlitzMax. You'll have to change HandleTestStart from a method to a function.