how are C# object references represented in memory / at runtime (in the CLR)?

后端 未结 2 862
庸人自扰
庸人自扰 2021-02-07 16:26

I\'m curious to know how C# object references are represented in memory at runtime (in the .NET CLR). Some questions that come to mind are:

  1. How much memory doe

2条回答
  •  难免孤独
    2021-02-07 17:05

    This answer is most easily understood if you understand C/C++ pointers. A pointer is a simply the memory address of some data.

    1. An object reference should be the size of a pointer, which is normally 4 bytes on a 32-bit CPU, and 8 bytes on a 64-bit CPU. It is the same regardless of where it is defined. Where it lives does depend on where it is defined. If it is a field of a class, it will reside on the heap in the object it is part of. If it is a static field, it is located in a special section of the heap that is not subject to garbage collection. If it is a local variable, it lives on the stack.

    2. An object reference is simply a pointer, which can be visualized as an int or long containing the address of the object in memory. It is the same regardless of where it is defined.

    3. This is implemented as a pointer to a pointer. The data is the same - just a memory address. However, there is no object at the given memory address. Instead, there is another memory address, which is the original reference to the object. This is what allows a reference parameter to be modified. Normally, a parameter disappears when its method completes. Since the reference to the object is not a parameter, then changes to this reference will remain. The reference to a reference will disappear, but not the reference. This is the purpose for passing reference parameters.

    One thing you should know, value types are stored in place (there is no memory address, instead they are stored directly where the memory address would be - See #1). When they are passed to a method, a copy is made and that copy is used in the method. When they are passed by reference, a memory address is passed which locates the value type in memory, allowing it to be changed.

    Edit: As dlev pointed out, these answers are not the hard and fast rule, since there is no rule that says this is how it must be. .NET is free to implement these questions however it wants. This is the most likely way to implement it though, as this is how the Intel CPU's work internally, so using any other method would likely be inefficient.

    Hope I didn't confuse you too much, but feel free to ask if you need clarification.

提交回复
热议问题