How to access locals through stack trace? (Mimicking dynamic scope)

后端 未结 2 2147
醉梦人生
醉梦人生 2021-02-16 00:07

Background

Even though it\'s possible to compile C# code at runtime, it\'s impossible to include and run the generated code in the current scope. Instead all variables

2条回答
  •  时光说笑
    2021-02-16 00:45

    So my question is whether it's possible to mimic dynamic scope in .NET through the use of reflection.

    Reflection enables run-time manipulation of items which are expressed in the metadata of an assembly.

    Local variables are not items expressed in the metadata of an assembly.

    The answer to your question is therefore "no".

    (How) is it possible to reliably access the locals of calling methods?

    A device which accesses the locals of a calling method is called a "debugger". So the answer to your question is "write yourself a debugger".

    Note that debuggers do not reliably access locals in a world with code optimizations. Locals can be optimized away, the jitter can generate code which uses the same register for two different locals, stack frames can be re-used during tail calls, and so on. And of course, you'd better have the PDB file that tells the debugger what the names associated with each stack frame location are.

    What your method would have to do is start up your custom debugger as a new process, and then wait for the debugger to send it a message. The debugger would then suspend the threads of the original process, do the interrogation of the stack frames, and then resume the threads of the process. It would then send messages to the debuggee that contain the information you've discovered. Since the debuggee is sitting there in a wait state waiting for the messages, it would then resume its business.

    If what you want is an in-process "eval" capability, consider JScript.NET, a language that was designed for that sort of thing.

提交回复
热议问题