xxxxxxxxxx
alias MyDelegate = void delegate();
void main()
{
int local;
MyDelegate dlg = () { import std.stdio; writeln("delegate ", local); };
// T.sizeof gives the size of a variable on the stack, so we get the size
// of the delegate summing together context pointer and function pointer
// (and potentially additional ABI things depending on the compiler/target)
// `.dup` copies the bytes from the stack stored for the delegate to the
// heap, but it doesn't pin the context pointer or anything similar which
// would however make this a safer operation.
auto heap = (cast(ubyte*)&dlg)[0 .. MyDelegate.sizeof].dup.ptr;
local = 5;
callHeapDlg(heap);
}
void callHeapDlg(ubyte* heap)
{
// This could be a potentially unsafe cast if casting to some other delegate!
// You might be casting away safety attributes or other things. Best to
// restrict the type of the delegate you convert to heap from the start.
// Simply recreates the delegate by casting a pointer to the bytes you have
// copied to a pointer to a delegate object and then dereferencing it.
// This copies the pointers from the heap back to the stack here.
auto dlg = *(cast(MyDelegate*) heap);
dlg(); // prints "delegate 5"
}