get pointer of member function delphi

delphi, function, lazarus, pointers

Solution

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.

Problem

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!

Original source