用地址调用方法时参数传递的一个错误 ( 积分: 50 )

  • 主题发起人 主题发起人 Baggiopw
  • 开始时间 开始时间
B

Baggiopw

Unregistered / Unconfirmed
GUEST, unregistred user!
Form1有一个方法成员function add( a,b:integer):integer;
function TForm1.add( a, b: integer): integer;
begin
result:=a+b;
end;

定义 TComputeFunction=function ( a,b:integer): integer;
然后var proc:TComputeFunction;
@proc:=form1.MethodAddress('add');
然后调用proc(1,2);结果返回不是3
在调试中发现传递到add函数中的参数值不是1,2,why?
 
原理我说不清楚,不过一般做法是这样的,注意最后的object
TComputeFunction=function ( a,b:integer): integer of object;

也就是:
unit Unit1;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;

type
TComputeFunction=function ( a: Integer
b:integer): integer of object;

TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
private

{ Private declarations }
public
{ Public declarations }
published
function add(a: Integer
b: integer): integer;
end;

var
Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
var
proc:TComputeFunction;
begin
proc := nil;
@proc:=form1.MethodAddress('add');
if Assigned(proc) then
proc(1, 5);
end;

function TForm1.add( a: Integer
b: integer): integer;
begin
result:=a+b;
end;

end.
 
对象方法默认的第一个参数是self即虚方法表指针,如果通过地址调用对象方法需要传递self参数,如下:
type
TForm1 = class(TForm)
Button1: TButton;
Label1: TLabel;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
published
function add(a, b: integer): Integer;
end;

TComputeFunction = function (_self: Pointer
a,b: Integer): Integer;
var
Form1: TForm1;
proc: TComputeFunction;

implementation

{$R *.dfm}

function TForm1.add(a, b: integer): Integer;
begin
Result :=a+b;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
proc:= MethodAddress('add');
Label1.Caption := IntToStr(proc(Self, 1,2));
end;
 
嘿嘿,原来如此,非常感谢!
 

Similar threads

S
回复
0
查看
3K
SUNSTONE的Delphi笔记
S
S
回复
0
查看
2K
SUNSTONE的Delphi笔记
S
S
回复
0
查看
1K
SUNSTONE的Delphi笔记
S
后退
顶部