[fpc-pascal] Dynamic messaging in Delphi
Luiz Americo Pereira Camara
luizmed at oi.com.br
Wed Jul 25 00:26:22 CEST 2012
Em 24/7/2012 11:13, Ryan Joseph escreveu:
> 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.
if delegate.GetInterface(IMyInterface, intfDelegate) then
intfDelegate.DoThis
Luiz
> 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
>
> _______________________________________________
> fpc-pascal maillist - fpc-pascal at lists.freepascal.org
> http://lists.freepascal.org/mailman/listinfo/fpc-pascal
>
More information about the fpc-pascal
mailing list