你可以使用
静止的
关键字。但它只能在新的Delphi版本中使用。
这样地:
type
TMyThread = class
private
// ...
class function ThreadProc(Param: Pointer): DWord; stdcall; static; // <- WinAPI call back
function Execute: DWord; // <- actual callback
public
constructor Create;
// ...
end;
{ TMyThread }
constructor TMyThread.Create;
begin
// ...
FHandle := CreateThread(nil, 0, @ThreadProc, Self, 0, FID);
end;
class function TMyThread.ThreadProc(Param: Pointer): DWord;
begin
Result := TMyThread(Param).Execute;
end;
function TMyThread.Execute: DWord;
begin
MessageBox(0, 'Hello from thread', 'Information', MB_OK or MB_ICONINFORMATION);
Result := 0;
end;
这里:threadproc是winapi回调例程。它需要某种形式的自定义参数,您可以在其中传递自我。它无法访问实例成员。这就是为什么它只是一个真正回调(execute)的包装器,它是类的一部分,可以访问它的字段和方法。