开发者

Anonymous methods cast as pointers

开发者 https://www.devze.com 2022-12-21 01:16 出处:网络
can anyone explain why the code below fails? type TIDEThemeObserverFunc = reference to procedure(foo: integer);

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)) <&g开发者_运维知识库t; -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.


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.


Anonymous methods are actually interfaces (more correct - objects implementing an interface).

Read more here: Anonymous methods in Delphi: the internals (written by Stackoverflow user Serg).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号