Manually allocate delegate?
userABCabc123 via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Fri Nov 20 16:30:44 PST 2015
On Sunday, 12 July 2015 at 09:03:25 UTC, Tofu Ninja wrote:
> On Sunday, 12 July 2015 at 08:47:37 UTC, ketmar wrote:
>> On Sun, 12 Jul 2015 08:38:00 +0000, Tofu Ninja wrote:
>>
>>> Is it even possible?
>>
>> what do you mean?
>
> Sorry, thought the title was enough.
>
> The context for a delegate(assuming not a method delegate) is
> allocated by the GC. Is there any way to allocate the context
> manually.
Yes:
========================
class Foo
{
void bar(){writeln(__PRETTY_FUNCTION__);}
}
auto uncollectedDelegate(T, string name)(ref T t)
{
import std.experimental.allocator.mallocator;
struct Dg{void* ptr, funcptr;}
void* funcptr = &__traits(getMember, T, name);
void* ptr = cast(void*)t;
Dg* dg = cast(Dg*) Mallocator.instance.allocate(Dg.sizeof);
dg.ptr = ptr;
dg.funcptr = funcptr;
return dg;
}
void main(string[] args)
{
Foo foo = new Foo;
auto dg = uncollectedDelegate!(Foo, "bar")(foo);
auto tdg = cast(void delegate()*) dg;
(*tdg)();
}
========================
with just a type __traits(getMember,...) on a delegate will only
return the function address in the process image. so without the
context ptr, just like a static or a global function. Later you
set the context by hand, using a pointer to an instance.
More information about the Digitalmars-d-learn
mailing list