[fpc-pascal] Dynamic messaging in Delphi

Ryan Joseph ryan at thealchemistguild.com
Tue Jul 24 16:13:10 CEST 2012


I was asking on the Mac Pascal list if Delphi had any ways to invoke methods on objects which the class was unknown at compile time (like a class that invokes a user defined delegate commonly used in Cocoa Mac programming and I assume Delphi not knowing) and one user told me interfaces will work for this. Btw, I'm aware you can use strings to invoke methods with a single argument but I wanted something better since this has been a real drawback in Pascal for me in recent years.

The idea is Main.pas has a delegate class which implements IMyInterface and MyInterface.pas declares the interface and can invoke its methods using a generic delegate object (typed TObject). This is really typical of UI elements like a button that wants to tell a receiver an action occurred but doesn't know the class of the receiving object. Providing this example works it's sort of a workaround to multiple inheritence but I don't see that Pascal would be capable of this, i.e. simply type casting an object and forcing it to call a method that may or may not exist (I feel like I tried this before and got crashing).

He swears this works and no one else answered otherwise but I'm getting "Error: Class or Object types "TObject" and "IMyInterface" are not related" errors at the line shown below.

Any ideas? Thanks.

====================

{$mode delphi}
{$interfaces corba}

unit MyInterface;
interface

type
	IMyInterface = interface
		procedure DoThis (value: integer);
	end;
	
procedure InvokeDelegate (delegate: TObject);
	
implementation

procedure InvokeDelegate (delegate: TObject);
var
	intfDelegate: IMyInterface;
begin
	ERROR ====> intfDelegate := IMyInterface(delegate);
	intfDelegate.DoThis(1);
end;

end.

====================

{$mode delphi}
{$interfaces corba}

program Main;
uses
	MyInterface;

type
	TMyDelegate = class (TInterfacedObject, IMyDelegate)
		procedure DoThis (value: integer);
	end;

procedure TMyDelegate.DoThis (value: integer);
begin
	writeln('did this ', value);
end;

var
	delegate: TMyDelegate;
begin	
	delegate := TMyDelegate.Create;
	TestDelegate(delegate);
end.

Regards,
	Ryan Joseph
	thealchemistguild.com




More information about the fpc-pascal mailing list