How can I dynamically inject code into event handlers in Delphi?

前端 未结 5 2126
予麋鹿
予麋鹿 2020-12-17 00:31

For debugging / performance tests I would like to dynamically add logging code to all event handlers of components of a given type at run time.

For example, for all

5条回答
  •  孤街浪徒
    2020-12-17 01:06

    If the function or procedure in the component you want to 'hook' is declard virtual or dynamic it can be done in the following manner:

    Let's assume for arguments sake that you wantto see all AfterOpen's from TDataset. This event handler is called from the virtual method:

    procedure TDataSet.DoAfterOpen;
    

    Create a new unit UnitDatasetTester (typed it in manual)

    unit UnitDatasetTester;
    
    interface
    
    uses
      DB;
    
    type
      TDataset = class( DB.TDataset )
      protected
        procedure DoAfterOpen; override;
      end;
    
    implementation
    
    uses
      MySpecialLoggingUnit; 
    
    procedure TDataset.DoAfterOpen;
    begin
      inherited;
      SpecialLog.Add( 'Hello world' );
    end;
    

    If you do not use this unit all works without loggig. If you use this unit as the LASt unit in your uses list (at least AFTER the DB uses) you do have logging for all datasets in that unit.

提交回复
热议问题