Function pointers
BlitzMax Forums/BlitzMax Beginners Area/Function pointers
| ||
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? |
| ||
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. |
| ||
huh....I don't understand it. Where are you actually defining TrigFunction? Hmmmmf, I don't get the code example :-) |
| ||
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? |
| ||
Yep, that'll do it, with a call to Integrate (timestep). |
| ||
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! |
| ||
@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 ) |
| ||
This is cool |
| ||
How would you create and use an array or bank of function pointers? |