Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Anonymous methods cast as pointers

can anyone explain why the code below fails?

type TIDEThemeObserverFunc = reference to procedure(foo: integer);
var fObserverFuncs: TList<TIDEThemeObserverFunc>

function RegisterEventObserver(aObserverFunc: TIDEThemeObserverFunc): Pointer;
begin
  fObserverFuncs.Add(aObserverFunc);
  Result := @aObserverFunc;

  // line below somehow fails
  assert(fObserverFuncs.IndexOf(TIDEThemeObserverFunc(Result)) <> -1);
end;

I assumed anonymous methods can simply be casted and used around via pointers but that seems like a wrong assumption. Also, any resources explaining how the anonymous methods are implemented under the hood would be great. TIA.

like image 244
utku_karatas Avatar asked Dec 01 '25 01:12

utku_karatas


1 Answers

You should use PPointer(@aObserverFunc)^ instead of @aObserverFunc to avoid the failed assert.

@gabr: thanks for ref to my blog, but I should recommend first to read the Stackoverflow user Barry Kelly blog as a more competent source of information.

like image 109
kludg Avatar answered Dec 04 '25 00:12

kludg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!