get pointer of member function delphi

梦想的初衷 提交于 2019-11-30 18:38:20

问题


Is there some trick how to get pointer of a member function in Lazarus / delphi? I have this code which won't compile....

Error is in Delphi:
variable required

in Lazarus:
Error: Incompatible types: got "<procedure variable type of function(Byte):LongInt of object;StdCall>" expected "Pointer"


The code:

  TClassA = class
  public
      function ImportantFunc(AParameter: byte): integer; stdcall;
  end;

  TClassB = class
  public
     ObjectA: TClassA;
     ImportantPtr: pointer;
     procedure WorkerFunc;
  end;

  function TClassA.ImportantFunc(AParameter: byte): integer; stdcall;
  begin
     // some important stuff
  end;

  procedure TClassB.WorkerFunc;
  begin
     ImportantPtr := @ObjectA.ImportantFunc; //  <-- ERROR HERE
  end;

Thanks!


回答1:


A member function cannot be represented by a single pointer. It needs two pointers, one for the instance and one for the code. But that's implementation detail and you just need to use a method type:

type
  TImportantFunc = function(AParameter: byte): integer of object; stdcall;

You can then assign ImportantFunc to a variable of this type.

Since you are using stdcall I suspect you are trying to use this as a Windows callback. That's not possible for a member function. You need a function with global scope, or a static function.




回答2:


type
  TImportantFunc = function(AParameter: byte): integer of object;stdcall;

  ImportantPtr: TImportantFunc;

procedure TClassB.WorkerFunc;
begin
   ImportantPtr := ObjectA.ImportantFunc; //  <-- OK HERE
end;



回答3:


ObjectA.ImportantFunc is not a memory location, so address operator @ can't be applied to it - hence compiler error. It is 2 pointers, @TClassA.ImportantFunc (method code) and ObjectA (Self argument). An answer to your question depends on what you really need - code pointer, Self, both or none.


If you need just to scope a function name use static class method

TClassA = class
public
 class function ImportantFunc(Instance: TClassA; AParameter: byte): integer;
                                                               stdcall; static;
end;


来源:https://stackoverflow.com/questions/10460171/get-pointer-of-member-function-delphi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!