2012-05-05 57 views
3

有没有一些技巧如何获得成员函数的指针在Lazarus/delphi中? 我有这样的代码将不能编译....

错误是 德尔福:
variable required

在拉撒路 :
Error: Incompatible types: got "<procedure variable type of function(Byte):LongInt of object;StdCall>" expected "Pointer"获取成员函数的指针delphi


代码:

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; 

谢谢!

回答

3

成员函数不能用单个指针表示。它需要两个指针,一个用于实例,一个用于代码。但是这是实现细节,您只需要使用方法类型:

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

然后,您可以将ImportantFunc分配给此类型的变量。

由于您使用的是stdcall,我怀疑您试图将此作为Windows回调使用。这对于一个成员函数来说是不可能的。您需要一个具有全局范围的函数或一个静态函数。

+1

为什么它是不可能的?他可以将方法定义为'class'方法并将'TMethod.Code'指针作为回调函数传递?或不? – teran

+0

@大卫:你是对的。我想用它作为回调。但'TClassA'实际上是一个'TCollectionItem'(!)所以每个项目都必须有自己的窗口回调:(因此不可能在全局范围内定义它。这太可怕了,但我不能相信这是不可能的。 – Peter

+0

@teran必须是静态的,而不是类方法 –

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

    ImportantPtr: TImportantFunc; 

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

ObjectA.ImportantFunc不是内存的位置,所以操作者地址@不能被施加到它的 - 因此编译错误。它是2个指针,@TClassA.ImportantFunc(方法代码)和ObjectA(自变量)。你的问题的答案取决于你真正需要什么 - 代码指针,自我,两者或没有。


如果你只需要到作用域的函数名称中使用静态类方法

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