Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying the value of a reference to an object

In C++ it is fairly simple to display the actual value of a pointer to an object. For example:

void* p = new CSomething();
cout << p;

Is there a way to do something like this in .NET?

The value of doing this would/could only be educational, e.g. for purposes of demonstration as in displaying a value for students to see rather than just comparing for reference equality or null (nothing) to prove shallow copies, immutability etc.

like image 275
Paul Sasik Avatar asked Jan 23 '26 00:01

Paul Sasik


2 Answers

You can use GCHandle to get the address of a pinned object. The GC can move objects around so the only sensible address to get is one of a pinned object.

GCHandle handle = GCHandle.Alloc(obj, GCHandleType.Pinned);
Console.WriteLine(handle.AddrOfPinnedObject().ToInt32());
handle.Free();

Remember though that GCHandle will only pin objects that are primitive or blittable types. Some objects are blittable (and you can set it up for demo purposes so it works) but any reference type will not be blittable.

You'll need to add an explicit blittable description using [StructLayout(LayoutKind.Sequential)] or use the debugger to directly inspect addresses of object that do not meet these criteria.

like image 155
Ron Warholic Avatar answered Jan 24 '26 19:01

Ron Warholic


If this is for education purposes, I suggest you use a debugger instead. If you load SOS.dll (which is part of the .NET framework) into WinDbg or even Visual Studio, you can examine the actual objects in memory.

E.g. to list the heap use the !dumpheap -stat command. The !do command dumps a mananaged object on the specified memory address and so forth. SOS has numerous commands that will let you examine internal .NET structures, so it is a really useful tool for learning more about the runtime.

By using the debugger for this, you're not restricted to looking at demo applications. You can peek into the details of real applications. Also, you'll pick up some really useful debugging skills.

There are several excellent introductions to debugging using WinDbg + SOS. Check Tess' blog for lots of tutorials.

like image 22
Brian Rasmussen Avatar answered Jan 24 '26 19:01

Brian Rasmussen