Function pointers

BlitzMax Forums/BlitzMax Beginners Area/Function pointers

Sweenie(Posted 2004) [#1]
The Bmaxinfo on the frontpage mentions Function pointers.
Does this refer to passing pointers as parameters or the ability to get a pointer to a function?

What I'm trying to ask is...
Does Bmax support function callbacks and if it does, how would I get the address of a specific function?
Is there an AddressOf function?


Michael Reitzenstein(Posted 2004) [#2]
Here's a brief example of using function pointers:

Local TrigFunction!( x! )

TrigFunction = Sin
Print TrigFunction( 0.0 )

TrigFunction = Cos
Print TrigFunction( 0.0 )


I'm unsure of how to get the address of a function. Casting the function pointer to Byte Ptr doesn't work.


Jeroen(Posted 2004) [#3]
huh....I don't understand it.

Where are you actually defining TrigFunction?
Hmmmmf, I don't get the code example :-)


Sweenie(Posted 2004) [#4]
So if I got this right I could use it like this...

Local Integrate(timestep#)

Function IntegrateEuler(timestep#)
 'Do Euler integration
End Function

Function IntegrateRK2(timestep#)
 'Do RK2 integration
End Function

Function IntegrateRK4(timestep#)
 'Do RK4 integration
End Function

Select IntegrateMethod$
 Case "EULER"
  Integrate=IntegrateEuler
 Case "RK2"
  Integrate=IntegrateRK2
 Case "RK4"
  Integrate=IntegrateRK4
End Select



So whenever I call the Integrate function one of the three other functions are called depending on which of those I set the Function pointer to?


BlitzSupport(Posted 2004) [#5]
Yep, that'll do it, with a call to Integrate (timestep).


Knotz(Posted 2004) [#6]
Now this is neat:

Function my_eq(a:Int,b:Int)
	If a = b-1 Then Return True
	Return False
End Function

Function test_equal(a:Int,b:Int,eq_func(a:Int,b:Int))
	Return eq_func(a,b)
End Function

Print test_equal(1,2,my_eq)


kudos brl!


Robert(Posted 2004) [#7]
@Jeroen:

Step-by-Step:

Declare a function pointer called TrigFunction. TrigFunction isn't defined at the moment, all we have told the compiler is what it returns (a double float) and what parameters in accepts (a double float)
Local TrigFunction!( x! )


Set the function pointer to the "Sin" function. So whenever we call TrigFunction it will actually call the Sin function. Because TrigFunction (as defined above) and Sin both accept the same arguments and return the same data type, this is OK.
TrigFunction = Sin


Demonstrate calling TrigFunction, because TrigFunction now "points" at the Sin function, TrigFunction(0.0) is the same as Sin(0.0)

Print TrigFunction( 0.0 )


Now set TrigFunction to Cos instead, so that calling TrigFunction(0.0) is the same as Cos(0.0)
TrigFunction = Cos
Print TrigFunction( 0.0 )



ImaginaryHuman(Posted 2004) [#8]
This is cool


ImaginaryHuman(Posted 2004) [#9]
How would you create and use an array or bank of function pointers?