Pointer to function...

BlitzMax Forums/BlitzMax Programming/Pointer to function...

Grey Alien(Posted 2006) [#1]
I'm sure many people ask this so sorry for asking again...

I would like to have a field within a type which is a pointer to a function. This can be set externally from the type and then when the type needs to call that function it can just use its field which contains the pointer. How can I do this please?

Thanks in advance.


splinux(Posted 2006) [#2]
Do you mean something like this:

Type t
  Field func()

  Function create:t(f())
    a:t=New t
    a.func=f
    Return a
  End Function
End Type




Function hi()
  Print "hi!"
End Function


Global g:t=t.create(hi)

g.func()



Dreamora(Posted 2006) [#3]
type test
field someFuncPtr(some:int, other:object)

method SetSomePtr(funcPtr(some:int, other:object))
someFuncPtr = funcPtr
end method
end type


Grey Alien(Posted 2006) [#4]
yes exactly like that and good different examples too, thanks :-). All I needed to know was () then, cool as I've done this before in Delphi and C++.

I also thought of a way to do it with objects whilst making some soup. Make a TFunction object with the a function called Func. Then you can extended TFunction (e.g. MyTFunction) and fill in your own Func by overriding the base one (unless params differ) and then your Test type can call MyTFunction.func() which will work polymorphically. However, this seems a tad lame compared to the direct method above...


Dreamora(Posted 2006) [#5]
But dont forget that the function references are type save.

So if you declare the field as function:int(int, object), you can only assign references to functions that return int and that need int, object (in this order) as input.


Grey Alien(Posted 2006) [#6]
yeah that's fine thanks.