How do I get the executing object for a stackframe?

后端 未结 3 1210
轻奢々
轻奢々 2021-01-01 22:55

When using reflection it is possible to obtain the call stack (apart from that it can be a crude approximation due to JIT optimizations) using System.Diagnostics.StackTrace

3条回答
  •  情歌与酒
    2021-01-01 23:33

    It's possible to obtain reference to thiscall object, but not with .NET code only. Native code must be involved. Even with using dynamic classes and System.Relection.Emit namespace .NET does not have instruments to access another methods evaluation stack and arguments.

    On other side if you disassemble your .NET method you can see that this reference does not passed on physical stack at all. Thiscall reference is stored in ECX(RCX for x64) register instead. So it is possible climb up on stack from your method to method from which you want to obtain thiscall object. And then lookup inside that method's machine codes for instruction which save register ECX (RCX) in stack, and get from that instruction relative address where that reference lies.

    Of course, the method of climbing is severely different in x32 and x64 application. To produce such function you must use not only C# but assembly code, and keep in mind that inline assembler is not allowed under x64; it must be a full assembler module.

提交回复
热议问题