For reference, I have reviewed the following questions: C# reusable function to dump current value of local variables, Find size of object instance in bytes in c#
However this question is a somewhat different take on the issue. Per this answer, local variables are stored on the stack (at least for value types).
My goal: A reusable method that could be called in any other method, and automatically produce a memory dump of only the local variables of that method. I am not necessarily looking for something that immediately returns objects - a raw byte array from memory is fine.
I do not want a full process dump, if at all possible.
What I have been trying:
My initial thought was that I could try to get the object memory addresses. I understand that the addresses of managed objects can be obtained by:
TypedReference tr = __makeref(obj);
return **(IntPtr**)(&tr);
However, I cannot figure out how to actually get the addresses of the local variables without manually calling this for every single variable.
I then thought about using the stack and the method information to determine how many local variables I needed, and the type. Using the following code, for example, I can get the method information:
catch (Exception ex)
var trace = new System.Diagnostics.StackTrace(ex);
var frame = trace.GetFrame(0);
var method = frame.GetMethod();
var locals = method.GetMethodBody().LocalVariables;
}
However, I am lacking information on how to get the latest data from the stack. I understand that this may be very complicated, but I am interested in seeing what can be done in C# without having to resort to external dependencies or third-party tools.
With that in mind, using either safe or unsafe code (documented or undocumented), is there a way to pop the last n items from the stack or to get the most recently added memory addresses?
If not, is there a better approach to accomplishing this goal?
Note: I just discovered SOS.DLL. Will this help?