.NET: Show the storage location or address of an object?

眉间皱痕 提交于 2019-12-11 06:48:24

问题


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...


回答1:


To make the demo meaningful, you need to pin the object first.

GCHandle handle = GCHandle.Alloc(o, GCHandleType.Pinned);
IntPtr address = handle.AddrOfPinnedObject();

I would demonstrate using SOS (part of the Debugging Tools for Windows package). You & your audience will actually gain some valuable skills that way, rather than just hand-waving about CLR implementation details.



来源:https://stackoverflow.com/questions/3124293/net-show-the-storage-location-or-address-of-an-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!