View source code Display the source code in core/memory.d from which this page was generated on github. Improve this page Quickly fork, edit online, and submit a pull request for this page. Requires a signed-in GitHub account. This works well for small changes. If you'd like to make larger changes you may want to consider using local clone. Page wiki View or edit the community-maintained wiki page associated with this page.

Function core.memory.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.

Prototype

static void addRoot(
  const(void*) p
) nothrow;

Parameters

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

Example

// 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…
}

Authors

Sean Kelly, Alex Rønne Petersen

License

Boost License 1.0

Comments