Interfaces as Function Pointers

Monkey Forums/Monkey Programming/Interfaces as Function Pointers

zoqfotpik(Posted 2012) [#1]
Does anyone have a code example of interfaces as function pointers?

I've tried implementing action objects but I haven't been able to get this working...


invaderJim(Posted 2012) [#2]
Shinkiro left a small example at the bottom of this thread: http://www.monkeycoder.co.nz/Community/posts.php?topic=3477

But if you need to see it in action, I've typed up a quickie

[monkeycode]
Interface Action
Method Execute:Void()
End

Function DoAction(action:Action)
action.Execute()
End


Class PrintSomething Implements Action
Method Execute:Void()
Print("Something")
End
End

Class PrintSomethingElse Implements Action
Method Execute:Void()
Print("Something else")
End
End

Function Main()
Local printSomething:PrintSomething = New PrintSomething()
Local printSomethingElse:PrintSomethingElse = New PrintSomethingElse()

DoAction(printSomething)
DoAction(printSomethingElse)

End
[/monkeycode]

So, basically, for each function callback you want to create, you have to define and instantiate a class. Lots of typing at times, but it gets the job done.


zoqfotpik(Posted 2012) [#3]
Thanks. I know I asked about this before (and maybe you answered, and maybe it was precisely the same answer...) but I've still been having trouble coming to grips with it. I will take another run at it with the aid of this code.

I've been reading a lot about design patterns.

One thing I've been thinking about after reading about Haskell and LISP is the idea of a pipe object, which would contain a number of function pointers and would take an operand object at one end of the pipe. Each function pointer would operate on the object and pass it on to the next.

Is this a common construct and are there any immediate uses that come to mind? This is also similar to UNIX pipes.


Samah(Posted 2012) [#4]
Real pipes would use a producer/consumer pattern. This is easy in Unix as each process would handle the produce and consume implementations. To do something like this in a single process, you need to either use threads, coroutines, or an awkward loop.

Monkey's default implementation does not support multithreading, nor coroutines, but Diddy has a subproject for threading if you want to take a look at it. Not all targets are supported, since not all targets support multithreading (ie. HTML5, Flash).

For maximum compatibility you may just want to use a single loop and alternate produce/consume. It's awkward, but it works.

http://en.wikipedia.org/wiki/Coroutine