2

So I've seen this question a few times about getting the physical address of a reference object in C# and the general consensus seems to be that this isn't possible since you can't call GCHandle.Alloc with GCHandleType.Pinned which will allow you to get the address of the pinned object.

What I find strange though is that in the Visual Studio debugger I can drag the object from the locals window to the Memory debug window and see the address and memory for a reference object. I can even type in the immediate window &obj and get the actual address of the object (this address correctly corresponds to the one shown in the Memory window).

However why is it I can't make the same call in my compiled code...ie:

object someObject = new Object();
&obj; // Compiler Error: Cannot take the address of, get the size of, or declare a pointer to a managed type ('object')

How is the Immediate\Memory Window allowed to get the address of managed types and even display the layout of memory but C# can't do any of this? Is there any way to get this actual address of a reference object in C#?

4

2 回答 2

3

The debugger has a great advantage over your own code. It can look at the process state while it is frozen with no code running. Getting the address of an object is thus not a problem, the garbage collector is not going to run to invalidate it.

于 2012-09-28T17:29:31.707 回答
0

The Carbage Collector handles the objects lifetime. It is also divided roughly into 3 'pieces' in memory, called gen0, gen1, gen2 (Generations).

In gen0 the fast living objects reside, where the allocated memory is small. The garbage collection is run frequently because there are many short lived objects there. If an object suvives gen0 it is moved to next gen.

When an object is garbaged collected all the other objects are re-arranged in memory, to keep the free memory space available.

But in gen2, where the biggest and long lived objects live, the memory is rarely re-arranged because it costs too much to move objects in gen2.

All this memory references and garbage collection is given to you for 'free' in a managed environment like C#.

Furthermore sometimes, optimizations are done, such as: "string interning".

于 2012-09-28T17:26:51.967 回答