www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Dynamic Method Dispatch

reply Derek Ney <derek hipgraphics.com> writes:
I am trying to write an interpreter for a dynamic language similar to Ruby
using D. I need to dynamically dispatch a method call to an object method. I
really just need a method pointer for this. Something like this:

CallMethod(receiver,methodname, methodarg)
{
  methodptr mp = lookup_method(methodname);

  return receiver.mp(methodarg);
}

I just can't see how I can do this with a delegate cause the receiver is
dynamic.
I need a table mapping methodname to a method pointer that is not tied
a particular instance. In a sense I could use a delegate if I could do this:

CallMethod(receiver,methodname, methodarg)
{
  delegate dg = lookup_method(methodname);

  dg.ptr = reciever;

  return dg(methodarg);
}

But I do not think you can do that nor is it thread safe nor pretty.
Any ideas of how to do this cleanly? Seems like it should be simple.
If there is a method pointer syntax it would be simple.
-Derek
Jan 20 2007
parent "Jarrett Billingsley" <kb3ctd2 yahoo.com> writes:
"Derek Ney" <derek hipgraphics.com> wrote in message 
news:eou8dj$1o2a$1 digitaldaemon.com...

 I just can't see how I can do this with a delegate cause the receiver is 
 dynamic.
 I need a table mapping methodname to a method pointer that is not tied
 a particular instance. In a sense I could use a delegate if I could do 
 this:

 CallMethod(receiver,methodname, methodarg)
 {
  delegate dg = lookup_method(methodname);

  dg.ptr = reciever;

  return dg(methodarg);
 }

You can actually (though maybe not with GDC? it's perfectly legal in DMD, but I thought I might have heard that it doesn't compile under GDC..).
 But I do not think you can do that nor is it thread safe nor pretty.
 Any ideas of how to do this cleanly? Seems like it should be simple.
 If there is a method pointer syntax it would be simple.

Nope, this is the only way to do unbound delegates. Some people have propose a genuine syntax for specifying the context pointer of the delegate when it's called, but nothing's come of it as of yet.
Jan 20 2007