What's the method representation in memory?

前端 未结 3 1486
萌比男神i
萌比男神i 2020-11-28 06:31

While thinking a little bit about programming in Java/C# I wondered about how methods which belong to objects are represented in memory and how this fact does concern multi

3条回答
  •  北荒
    北荒 (楼主)
    2020-11-28 07:31

    I am going to try to answer this in the context of C#.There are basically 3 different types of Methods

    • virtual
    • non-virtual
    • static

    When your code is executed, you basically have two kinds of objects that are formed on the heap.

    • The object corresponding to the type of the object. This is called Type Object. This holds the type object pointer, the sync block index, the static fields and the method table.
    • The object corresponding to the object itself, which contains all the non static fields.

    In response to your questions,

    1. Is a method instantiated for each object in memory seperately or do all objects of the same type share one instance of the method?

    This is a wrong way of understanding objects. All methods are per type only. Look at it this way. A method is just a set of instructions. The first time you call a particular method, the IL code is JITed into native instructions and saved in memory. The next time this is called, the address is picked up from the method table and the same instructions are executed again.

    2.If the latter, how does the executing thread know which object's attributes to use? Each static method call on a Type results in looking up the method table from the corresponding Type Object and finding the address of the JITed instruction. In case of methods that are not static, the the relevant object on which the method is called is maintained on the thread's local stack. Basically, you get the nearest object on the stack. That is always the object on which we want the method to be called.

    3.Is it possible to modify the code of a method in C# with reflection for one, and only one object of many objects of the same type? No, It is not possible now. (And I am thankful for that). The reason is that reflection only allows code inspection. If you figure out what some method actually means, there is no way you are going to be able to change the code in the same assembly.

提交回复
热议问题