Member function pointers

bitwise via Digitalmars-d digitalmars-d at puremagic.com
Wed Sep 9 16:11:00 PDT 2015


On Wednesday, 9 September 2015 at 18:33:41 UTC, Prudence wrote:
> On Tuesday, 27 May 2014 at 12:21:40 UTC, d coder wrote:
>> [...]
>
> What's the current state of this? I'm in need of such behavior 
> for win32 interop.
>
> I'm thinking that one can make the above code more general by 
> using it in a mixin and automatically generating the funcptr 
> signature:
>
>
> import std.stdio;
> import std.concurrency;
>
> extern (C) int getch();
> import std.string;
>
>
> template FancyDelegate(O, D)
> {
> 	const char[] FancyDelegate = "union "~O.stringof~"Delegate { 
> "~D.stringof~" dg; struct { "~O.stringof~"* ptr; 
> "~D.stringof.replace("delegate(", 
> "function("~O.stringof~",").replace(",)", ")")~" funcptr; } }";	
> 	//const char[] FancyDelegate = "union "~O.stringof~"Delegate { 
> "~D.stringof~" dg; struct { "~O.stringof~"* ptr; 
> "~D.stringof.replace("delegate(", "function(")~" funcptr; } }";	
> }
>
> class X
> {
> 	public int z = 2;
> 	public void foo(int x)
> 	{
> 		//writeln(this.z*x);
> 		writeln(x);
> 	}
> }
>
> void delegate(int) dg;
>
> mixin(FancyDelegate!(X, typeof(dg)));
>
>
> void main()
> {
>
> 	auto xX = new X();
> 	XDelegate x;
> 	x.dg = &xX.foo;
> 	
> 	//x.dg(3);
> 	x.ptr = &xX;
> 	x.funcptr(xX, 5);
> 	//x.funcptr(5);
>
> 	
> 	getch();
> }
>
> Unfortunately this fails when entering the function. I've tried 
> various things(passing &xX, etc..., passing nothing(the 
> comments, etc.)
>
> I thought a delegate, when called, was called like a member 
> function? It seems that a delegate is some magic black box that 
> we can't emulate in any way shape or form due to the calling 
> conventions used?

struct S {
	void fun() { writeln("fun" ); }
}

class C {
	void fun() { writeln("fun" ); }
}

void main(string[] args) {
	S s;
	void delegate() fn1 = &s.fun;
	fn1();

	C c = new C();
	void delegate() fn2 = &c.fun;
	fn2();

	void delegate() fn3;
	fn3.ptr = cast(void*)&s;
	fn3.funcptr = &S.fun;
	fn3();

	void delegate() fn4;
	fn4.ptr = cast(void*)c;
	fn4.funcptr = &C.fun;
	fn4();
}


More information about the Digitalmars-d mailing list