Is there a way to get the "address" of an object? This is for demonstration purposes, I know this is a bad idea in general and if it works at all then as unsafe
code. The project is tuned to allow unsafe code. However my tries were unsuccessful. The code I have so far is not compiling:
unsafe static String AddressOf(Object o)
{
void* p = &o;
return String.Format("{0}", new IntPtr(p));
}
Error: Cannot take the address of, get the size of, or declare a pointer to a managed type ('object')
Even if The memory address cannot be retrieven, then maybe a memory slot or something else showing the location of that object.
Background: my intention is to make some demo showing the differences between passing by value or by reference and dump the location of these objects.
ADDED 2010-06-27:
I finally abandonned the idea of doing it from within the .NET program itself. Seems not to lead to any good solution. Even if it had worked it would have cluttered the code so much that you can barely explain the result in simple ways and use it for some demo purpose. I would now like to do it with a good (meaning CLR aware) debugger in the way that is adviced in the answer below.
Debugging can be improved inside VS by activating an option in the configuration settings Enable Unmanaged Debugging
, unfortunately not available in the free express edition of visual studio (the only version I have at home right now). Is there a way to make Enable Unmanaged Debugging
work manually?
After struggling a bit I installed Debugging Tools for Windows which provided me the WinDbg. Great tool I used years ago for driver development. Now it's part of a huge package. I tried to follow the instructions to get the SOS.DLL way working without success. I cannot even find this DLL. Even this solution seems to require the Enable Unmanaged Debugging
flag in the project...