View source code
Display the source code in core/memory.d from which this
page was generated on github.
Report a bug
If you spot a problem with this page, click here to create a
Bugzilla issue.
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.
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.
static void addRoot
(
const(void*) p
) nothrow @nogc;
If p is null, no operation is performed.
Parameters
Name | Description |
---|---|
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
Copyright © 1999-2022 by the D Language Foundation | Page generated by ddox.