Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the unit name of a class if I have the class / VMT address only

Tags:

delphi

As I read here,

the VMT also contains a number of “magic” fields to support features such as parent class link, instance size, class name, dynamic method table, published methods table, published fields table, RTTI table, initialization table for magic fields, the deprecated OLE Automation dispatch table and implemented interfaces table

It looks like the VMT does not include a field which contains the unit name where the class is defined. Is there some 'compiler magic' involved?

like image 634
mjn Avatar asked Jun 30 '12 10:06

mjn


2 Answers

I cannot see why the VMT should be involved here. TObject already exposes a class function UnitName for that.

System.TObject.UnitName

like image 134
Uwe Raabe Avatar answered Nov 15 '22 08:11

Uwe Raabe


VMT includes a pointer to class RTTI (provided by ClassInfo method); class RTTI includes a class unit name. As an exercise you can get unit name from VMT pointer, I have written this (tested on Delphi XE):

uses TypInfo;

type
  TObj = class

  end;

procedure TForm1.Button3Click(Sender: TObject);
var
  Obj: TObj;    //  dummy obj instance
  VMT: Pointer;
  P: Pointer;   // class info

begin
// you can get VMT pointer so
  Obj:= TObj.Create;
  VMT:= PPointer(Obj)^;
  Obj.Free;
// or so
  VMT:= Pointer(TObj);

  P:= PPointer(PByte(VMT) + vmtTypeInfo)^;
  if P <> nil then
    ShowMessage(GetTypeData(P).UnitName);
end;
like image 38
kludg Avatar answered Nov 15 '22 08:11

kludg