Get delphi member function pointer

Is there any trick how to get a pointer to a member function in Lazarus / delphi? I have this code that will not compile ....

Error in Delphi:
variable required

in Lazare:
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;

Thank!

+3
source share
3 answers

A member function cannot be represented by a single pointer. Two pointers are needed for this, one for the instance and one for the code. But this implementation detail and you just need to use the type of method:

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

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

stdcall, , Windows. -. .

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

  ImportantPtr: TImportantFunc;

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

ObjectA.ImportantFunc , - @ - , . 2 , @TClassA.ImportantFunc ( ) ObjectA (Self ). , - , "", .


,

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

All Articles