Is there a way I can get that called my method from the call stack?

S

Sherif ElMetainy

Hello

Using the System.Diagnostics.StackTrace class (see code below), I can know
that method that called my currently executing method. Is there a way I can
get a reference to the object instance used to call the method, i.e. the
this pointer for the calling method? I searched the FCL documentation for
such a method, but I didn't find any. Do I have to use Unmanaged code?

public class C2 {
public static void M1()
{
// here I can get the method that called my method
MethodInfo callingMethod = new StackTrace().GetFrame(1).GetMethod();
object callingObject; // I need to know how can I get a reference to
the calling object.
}
}

Note: My application will run using full trust, and normal user (not
Administrator) privileges.
Best regards,
Sherif
 
A

Anders Norås [MCAD]

Using the System.Diagnostics.StackTrace class (see code below), I can know
that method that called my currently executing method. Is there a way I
can
get a reference to the object instance used to call the method, i.e. the
this pointer for the calling method? I searched the FCL documentation for
such a method, but I didn't find any. Do I have to use Unmanaged code?

If your method is called via COM interop the caller probalbly isn't managed
code and has no "this" reference. If your method is called from a project
which has been compiled with JIT optimizations enabled you have no guarantee
that the "this" reference will be on the stack. If your method is solely
called from managed code compiled without JIT optimizations, the reference
should be on the stack.
Unfortunantly, there is no way of finding this reference on the stack using
managed code. You could be able to gain access to the reference using the
Windows Debugging API, but again there are no guarantees that you'll find
the callers "this" reference and the debugging API is complicated to use.

I suggest that you just pass the callers reference as a parameter to the
method(s) where you need to access the callers instance.

Anders Norås
http://dotnetjunkies.com/weblog/anoras/
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top