GLBasic forum

Main forum => GLBasic - en => Topic started by: shaftusmaximus on 2009-Aug-12

Title: Use of addressof()?
Post by: shaftusmaximus on 2009-Aug-12
I'd like to be able to pass in function addresses to other functions and use them.  addressof() will give me a function's address... but unfortunately I've only seen addressof() used for passing in a function address to sortarray().  I can't look inside sortarray() to see how it handles having the function address passed to it.  I can't figure out how to dereference or properly use the passed in function address (is it possible?).

Here is some quick example code which doesn't work:


// just a meaningless function for testing
x = ADDRESSOF(whatever)

// just some meaningless test data
DIM y[8]
y[0] = 0
y[1] = 1

// the type of meaningful thing I'd like to be able to do
map(x,y)

FUNCTION whatever: i
ENDFUNCTION

// the error here is "call to undefined function : x
FUNCTION map: x, y
   FOREACH i IN y[]
      x(i)
   NEXT
ENDFUNCTION
Title: Re: Use of addressof()?
Post by: Kitty Hello on 2009-Aug-12
No, that's not possible. I mean, yes it is with INLINE, but hey, that's pretty bad.

I see that having a function pointer might be of some value. Your example showed that. But it's not BASIC and it's not possible so far.
Title: Re: Use of addressof()?
Post by: shaftusmaximus on 2009-Aug-13
QuoteNo, that's not possible. I mean, yes it is with INLINE, but hey, that's pretty bad.

Thanks!

QuoteI see that having a function pointer might be of some value. Your example showed that. But it's not BASIC and it's not possible so far.

Ahhh.  Well I'm not an expert on BASIC by any means (I come from a background of C, Smalltalk, Prolog, etc).  I just had a question on how to do something.  Thanks for your answer!  And now I know that if I want to do something like that, I can always INLINE it....
Title: Re: Use of addressof()?
Post by: shaftusmaximus on 2009-Aug-13
It looks like CALLBYNAME would be an easy way to do this, if CALLBYNAME also worked on functions (which I think it doesn't?).  Then you would just pass in the name of the function instead of a pointer....

// Something like this
FUNCTION map: x, y
   FOREACH i IN y[]
      CALLBYNAME(x, i)
   NEXT
ENDFUNCTION

Title: Re: Use of addressof()?
Post by: Moru on 2009-Aug-13
Sadly you can't call a function with CALLBYNAME(). Use global variables to store the parameters.
Title: Re: Use of addressof()?
Post by: Kitty Hello on 2009-Aug-13
Yes, the main problem with function pointer is: You must know the "type" of the function, means the parameter count and type plus return type. You can use a function pointer for int foo() to call a function that might look like char* bar(int, int, char); It will crash, however.

I think of a way to get proper callbacks, though. It would simplify a lot of other uses.