回调函数的问题~(50分)

  • 主题发起人 主题发起人 logpie
  • 开始时间 开始时间
L

logpie

Unregistered / Unconfirmed
GUEST, unregistred user!
先祝大家新年好啊!哈哈哈
大家看看下面代码:
(1)DLL的:
library StrSrchLib;
uses
Wintypes,
WinProcs,
SysUtils,
Dialogs;

type
{ declare the callback function type }
TFoundStrProc = procedure(StrPos: PChar); StdCall;---------------------(1)

function SearchStr(ASrcStr, ASearchStr: PChar; AProc: TFarProc): Integer; StdCall;
var
FindStr: PChar;
begin
FindStr := ASrcStr;
FindStr := StrPos(FindStr, ASearchStr);
while FindStr <> nil do
begin
if AProc <> nil then
TFoundStrProc(AProc)(FindStr);------------------------(2)
FindStr := FindStr + 1;
FindStr := StrPos(FindStr, ASearchStr);
end;
end;

exports
SearchStr;
begin
end.
(2)调用DLL的:
unit MainFrm;

interface

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

type
TMainForm = class(TForm)
btnCallDLLFunc: TButton;
edtSearchStr: TEdit;
lblSrchWrd: TLabel;
memStr: TMemo;
procedure btnCallDLLFuncClick(Sender: TObject);
end;

var
MainForm: TMainForm;
Count: Integer;

implementation

{$R *.DFM}

{ Define the DLL's exported procedure }
function SearchStr(ASrcStr, ASearchStr: PChar; AProc: TFarProc): Integer; StdCall external
'STRSRCHLIB.DLL';

{ Define the callback procedure, make sure to use the StdCall directive }
procedure StrPosProc(AStrPsn: PChar); StdCall;
begin
inc(Count); // Increment the Count variable.
end;

procedure TMainForm.btnCallDLLFuncClick(Sender: TObject);
var
S: String;
S2: String;
begin
Count := 0; // Initialize Count to zero.
SetLength(S, memStr.GetTextLen);
memStr.GetTextBuf(PChar(S), memStr.GetTextLen);
S2 := edtSearchStr.Text;
SearchStr(PChar(S), PChar(S2), @StrPosProc);
{ Show how many times the word occurs in the string. This has been
stored in the Count variable which is used by the callback function }
ShowMessage(Format('%s %s %d %s', [edtSearchStr.Text, 'occurs', Count, 'times.']));
end;
end.


问题一:在(1)中的
type
{ declare the callback function type }
TFoundStrProc = procedure(StrPos: PChar); StdCall;
是不是等同于Procedure TFoundStrProc (StrPos: PChar); StdCall;?
如果等同那么我把他替换成上述表达,为什么会在底下出错而无法编译?
如果不是请告之这样写法是什么意思?
问题二:在(2)中
TFoundStrProc(AProc)(FindStr);
TFoundStrProc后怎么接了2个()?这两个()里分别代表什么?
这样调用有什么意义?
 
问题一:
TFoundStrProc = procedure(StrPos: PChar); StdCall;
是声明了TFoundStrProc这样的一种数据类型,由于回调函数需要象变量一样使用,
因此必需预先声明这样的一个数据类型,而
Procedure TFoundStrProc (StrPos: PChar); StdCall;
只是定义了一个过程的接口
问题二:
TFoundStrProc后面的第一个()代表将变量AProc的类型强制转换为TFoundStrProc,
而第二个()则是过程AProc所需的参数,意义完全不一样
 
接受答案了.
 
后退
顶部