Function Pointer as Parameter
BlitzMax Forums/BlitzMax Programming/Function Pointer as Parameter
| ||
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) |
| ||
nvm looks like i just had to declare it like a functionFunction SayHello() Print "Hello" End Function Function InsertFunction(a()) a() End Function InsertFunction(SayHello) |
| ||
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. |
| ||
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 ) |
| ||
Ah that's a neat trick as well. |
| ||
....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. |