Hi,
I managed to hook an object construction with the following code. Each time I construct a new object I add it to a list. I used the following code
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, madCodeHook, StdCtrls, ContNrs, ExtCtrls;
type
TA = class
end;
TB = class
end;
TC = class
end;
TProxyA = class
A : TA;
end;
TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
Button3: TButton;
Panel1: TPanel;
Button4: TButton;
Button5: TButton;
Button6: TButton;
procedure Button1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure Button4Click(Sender: TObject);
private
procedure Hola;
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
var
l : TObjectList;
d : function: TObject;
po,ph,p : procedure of object;
procedure RegisterInstance(o : TObject);
var
s : string;
p : TProxyA;
Begin
s := o.ClassName;
if (s='TA') or (s='TB') or (s='TC') then
Begin
l.add(o);
end;
end;
function MyInit: TObject;
Begin
result := d;
RegisterInstance(result);
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
HookCode(@TObject.NewInstance,@MyInit,@d);
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
l := TObjectList.Create;
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
TA.Create();
TA.Create();
TB.Create();
TC.Create();
end;
procedure TForm1.Button3Click(Sender: TObject);
var
i : integer;
begin
for i:=0 to l.Count-1 do
Begin
ShowMessage(l.ClassName);
end;
end;
Now I've been tying to hook the object destruction to remove it from the list I mentioned before. I tryied without success. Can anyone help me?
By the way, is the code I wrote safe?
Esteban
Hook Destructor
Some comments:
(1) In RegisterInstance you should ask whether the object is <> nil. Normally it should always be <> nil, but you should check just to be sure.
(2) If an object TA, TB or TC is created from within different threads at the same time, you have a problem. You need to synchronize access to the object list then. As long as it's all the same problem, things should be fine, though.
(3) The destructor has a hidden "Self: TObject" parameter.
(1) In RegisterInstance you should ask whether the object is <> nil. Normally it should always be <> nil, but you should check just to be sure.
(2) If an object TA, TB or TC is created from within different threads at the same time, you have a problem. You need to synchronize access to the object list then. As long as it's all the same problem, things should be fine, though.
(3) The destructor has a hidden "Self: TObject" parameter.