Is there a way to determine if a reference to an object procedure corresponds to the object instance in Pascal?

Viewed 78

I have a not very good solution for this task, but can someone tell me how to use the standard library or a more elegant approach. The current solution is based on the fact that the reference to the procedure of the object stores two pointers in memory, a pointer to the procedure code and a pointer to the object.

function IsObject( const AEvent: TNotifyEvent; const AObject: TObject ): Boolean;
begin
  Result := PointerArray( Pointer( @AEvent )^ )[1] = Pointer( AObject );
end;
1 Answers

I'd use the TMethod record declared in the System unit. The record contains two member fields of type Pointer - Code and Data, that allow you to pick out the two pointers of the method. In your case, you need the Data member, which is the method's subject:

function ObjectIsMethodSubject(AObject: TObject; AEvent: TNotifyEvent): Boolean;
begin
  Result := TMethod(AEvent).Data = AObject;
end;
Related