Understanding behavior of member functions loaded at runtime
Ali Çehreli via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Wed Mar 18 11:07:19 PDT 2015
On 03/18/2015 09:02 AM, Maeriden wrote:
> On Wednesday, 18 March 2015 at 07:57:39 UTC, Kagamin wrote:
>> You violate the ABI, try to use delegates instead of functions.
>
> I'm sorry,I don't understand what you mean.
The types that you cast to are not correct. In D, callable member
function pointers are delegates, a type that combines a function pointer
and a context.
import std.stdio;
struct S
{
int a;
int b;
int method()
{
writeln(&a);
return a + b;
}
}
void main()
{
auto s = S(1, 1);
auto func = &s.method; // <-- note lowercase s
static assert ( is (typeof(func) == int delegate()));
static assert (!is (typeof(func) == int function())); // <-- note !
assert(func() == 2);
}
The function pointer and the context pointer are available through the
.funcptr and .ptr properties of the delegate. It is possible to make a
delegate by setting those properties:
void main()
{
auto s = S(1, 1);
auto func = &S.method; // <-- note uppercase S
static assert (!is (typeof(func) == int delegate())); // <-- note !
static assert ( is (typeof(func) == int function()));
int delegate() d; // let's make a delegate
d.funcptr = func;
d.ptr = &s;
assert(d() == 2);
}
Ali
More information about the Digitalmars-d-learn
mailing list