Function Pointer as Parameter

BlitzMax Forums/BlitzMax Programming/Function Pointer as Parameter

BLaBZ(Posted 2012) [#1]
Is it possible to pass a function pointer in as a function parameter?

Example:

Function SayHello()
	Print "Hello"	
End Function


Function InsertFunction(a:Int Ptr)
	a()
End Function 

InsertFunction(SayHello)



BLaBZ(Posted 2012) [#2]
nvm looks like i just had to declare it like a function

Function SayHello()
	Print "Hello"	
End Function



Function InsertFunction(a())
	a()
End Function 

InsertFunction(SayHello)



Htbaa(Posted 2012) [#3]
When you want to pass a function that requires parameters you need to make sure the signature of InsertFunction also matches that of the passed function. So if you want to pass a function with several parameters it needs to be defined that way as well, e.g. InsertFunction(a(foo:Int, bar:Int)). I'm doing this without testing it, so the syntax might be a bit different.

Point is, whilst it is useful it does get ugly very fast imo.


GW(Posted 2012) [#4]
You don't always need to define the callback signature in the arguments though. I agree it can get ugly pretty fast if you're not careful.
SuperStrict 
Framework brl.basic

Function myfunc#(a#)
	Print a
End Function

Function Caller(p:Byte Ptr)
	Local fp(a#) = p
	fp(123.0)
End Function

Local _ptr:Byte Ptr = myfunc
 Caller( _ptr ) 



Htbaa(Posted 2012) [#5]
Ah that's a neat trick as well.


Yasha(Posted 2012) [#6]
....just be wary that if you cast a function pointer through Byte Ptr to a function pointer of a different signature, there's a chance of all hell breaking loose as it may corrupt the stack and registers. Do not do this under any circumstances.

In the example above, it probably makes no difference in this specific case, and anyway I assume it's a typo (although that does highlight how easy it is to break SuperStrict once you start using Byte Ptr), but fp and myfunc have different signatures.