Get a Reference to an Object's Monitor

Timon Gehr timon.gehr at gmx.ch
Tue Dec 20 17:03:28 PST 2011


On 12/21/2011 01:27 AM, bearophile wrote:
> Timon Gehr:
>
>> The vptr is used to implement dynamic method calls.
>> Therefore it might not correspond to the static type of
>> the reference and has to be an instance attribute.
>
> Right. In that old enhancement request I was asking for __vptr to be both a class attribute and instance attribute.
>

__vptr is not even a documented feature, so your request seems strange 
to me.

>
>> Why would you have to manipulate vptr?
>
> To quickly know what's the class of a class instance that's on the heap, to avoid structs because I sometimes need virtual methods, and avoid initializing another field just for this purpose. It's for a special usage.
>
>
>> You can use typeid to compare
>> instances for identity of their corresponding type.
>
> I think I need something more light.
>

class A{}
class B: A{}
void main(){
     A a = new B;
     assert(typeid(a) is typeid(B));
}


>
>> Anyway, to get the vptr of a class C, do this:
>>
>> void** vptr = typeid(C).vtbl.ptr;
>
> I will compare this to the solution I have used to safe.
> Creating a class instance of TypeInfo just to know the value of what it looks like a static field (the head of the virtual table) seems strange.
>
? No class instance is created. typeid just gives a reference to the 
compiler generated typeinfo that is in the static data section.



More information about the Digitalmars-d mailing list