The OpenD Programming Language

GC.addRoot

Adds an internal root pointing to the GC memory block referenced by p. As a result, the block referenced by p itself and any blocks accessible via it will be considered live until the root is removed again.

If p is null, no operation is performed.

struct GC
extern (C) pragma(mangle, "gc_addRoot") static nothrow @nogc pure
void
addRoot
(
const void* p
)

Parameters

p void*

A pointer into a GC-managed memory block or null.

Examples

// Typical C-style callback mechanism; the passed function
// is invoked with the user-supplied context pointer at a
// later point.
extern(C) void addCallback(void function(void*), void*);

// Allocate an object on the GC heap (this would usually be
// some application-specific context data).
auto context = new Object;

// Make sure that it is not collected even if it is no
// longer referenced from D code (stack, GC heap, …).
GC.addRoot(cast(void*)context);

// Also ensure that a moving collector does not relocate
// the object.
GC.setAttr(cast(void*)context, GC.BlkAttr.NO_MOVE);

// Now context can be safely passed to the C library.
addCallback(&myHandler, cast(void*)context);

extern(C) void myHandler(void* ctx)
{
    // Assuming that the callback is invoked only once, the
    // added root can be removed again now to allow the GC
    // to collect it later.
    GC.removeRoot(ctx);
    GC.clrAttr(ctx, GC.BlkAttr.NO_MOVE);

    auto context = cast(Object)ctx;
    // Use context here…
}

Meta