Am 16.09.2022 um 03:53 schrieb Hairy Pixels:

On Sep 11, 2022, at 3:28 PM, Ondrej Pokorny via fpc-pascal 
<fpc-pascal@lists.freepascal.org> wrote:

You should be able to get the Invoke procedure pointer from the RTTI.
Sorry Sven mentioned this I must have glossed over it. So yes I am storing the 
function reference in a class so it’s not going to get freed.

Given this example here can you explain how to get the procedure pointer from 
the RTTI? Even so if you get the procedure pointer you need the class instance 
also, which reference must be keeping somewhere right?

type
   TProc = reference to procedure;
   TMyClass = class
     procedure DoThis;
   end;

var
   p: TProc;
   c: TMyClass;
begin
   c := TMyClass.Create;
   p := c.DoThis;
   // Can I get the refefence to "c" back using the RTTI?
end.


No, you can't get a reference to c, because the compiler will essentially create the following code:

=== code begin ===

type
  TProc = reference to procedure;
  TMyClass = class
    procedure DoThis;
  end;

  TCapturer = class(TInterfacedObject, TProc)
    m: procedure of object;
    procedure Anonymous1;

    procedure TProc.Invoke = Anonymous1;
  end;

var
  p: TProc;
  c: TMyClass;
  capturer: TCapturer;
  capturer_keepalive: IUnknown;
begin
  capturer := TCapturer.Create;
  capturer_keepalive := capturer;
  c := TMyClass.Create;
  capturer.m := @c.DoThis;
  p := capturer as TProc;
end.

=== code end ===

Regards,
Sven
_______________________________________________
fpc-pascal maillist  -  fpc-pascal@lists.freepascal.org
https://lists.freepascal.org/cgi-bin/mailman/listinfo/fpc-pascal

Reply via email to