Get the calling object or method in d

d

Solution

It's not directly possible to get information about your "caller". You might have some luck getting the address from the call stack, but this is a low-level operation and depends on things such as whether your program was compiled with stack frames. After you have the address, you could in theory convert it to a function name and line number, provided debugging symbols are available for your program's binary, but (again) this is highly platform-specific and depends on the toolchain used to compile your program.

As an alternative, you might find this helpful:

void callee(string file=__FILE__, int line=__LINE__, string func=__FUNCTION__)()
{
    writefln("I was called by %s, which is in %s at line %d!", func, file, line);
}

void caller()
{
    // Thanks to IFTI, we can call the function as usual.
    callee();
}

But note that you can't use this trick for non-final class methods, because every call to the function will generate a new template instance (and the compiler needs to know the address of all virtual methods of a class beforehand).

Problem

Somewhat related to my previous question here Is there a way to get the calling Object from within a function or method in d? example: ``` class Foo { public void bar() { auto ci = whoCalledMe(); // ci should be something that points me to baz.qux, _if_ baz.qux made the call } } class Baz { void qux() { auto foo = new Foo(); foo.bar(); } } ``` Questions: - Does something like `whoCalledMe` exist? and if so, what is it called? - if something does exist, can it be used at compile time (in a template) and if so, how? Alternatively; - is it possible to get access to the call stack at runtime? like with php's `debug_backtrace`?

Original source

Related problems