Thread overview
Calling class methods by pointers
Nov 22, 2010
wrzosk
Nov 23, 2010
Jesse Phillips
Nov 23, 2010
wrzosk
November 22, 2010
Is there any way to save pointer to class method, and call it later?

I know about ptr, and funcptr properties of delegates. I tried to change ptr and or funcptr manually after delegate was obtained. It worked in some situations. I don't know if it is a correct use of delegate:

import std.writeln;

class Foo
{
   string name;
   this(string e)
   {
       name = e;
   }
   void Print()
   {
       writeln("Print on ", name);
   }
   void Print2()
   {
       writeln("Print2 on ", name);
   }

}

auto foo = new Foo("foo");
auto dg = &foo.Print;
auto foo2 = new Foo("foo2");

dg();                        // Print on foo
dg.ptr = foo2;
dg();                        // Print on foo2
dg.funcptr = &Foo.Print2;
dg();                        // Print2 on foo2

The problem i see is that in funcptr there is real entry point for method used, not the index in virtual table, so the polymorphism can't work with that.

As I have written - i don't know whether it is correct use for delegate. Possibly the ptr, funcptr should be both const (Then is it possible to call method on object like in C++ ->* or .*?)
If not, then maybe delegates should work a little different.
November 23, 2010
wrzosk Wrote:

> The problem i see is that in funcptr there is real entry point for method used, not the index in virtual table, so the polymorphism can't work with that.
> 
> As I have written - i don't know whether it is correct use for delegate.
> Possibly the ptr, funcptr should be both const (Then is it possible to
> call method on object like in C++ ->* or .*?)
> If not, then maybe delegates should work a little different.

You would want something like:

dg();                        // Print on foo
dg = &foo2.Print;
dg();                        // Print on foo2
dg = &foo2.Print2;
dg();                        // Print2 on foo2

November 23, 2010
On 23.11.2010 01:22, Jesse Phillips wrote:
> wrzosk Wrote:
>
>> The problem i see is that in funcptr there is real entry point for
>> method used, not the index in virtual table, so the polymorphism can't
>> work with that.
>>
>> As I have written - i don't know whether it is correct use for delegate.
>> Possibly the ptr, funcptr should be both const (Then is it possible to
>> call method on object like in C++ ->* or .*?)
>> If not, then maybe delegates should work a little different.
>
> You would want something like:
>
> dg();                        // Print on foo
> dg =&foo2.Print;
> dg();                        // Print on foo2
> dg =&foo2.Print2;
> dg();                        // Print2 on foo2
>
That's obvious to me how to use is. But what is the purpose of read write ptr and funcptr ?