我在调用CreateThread时将类引用作为参数传递给ThreadProc时遇到问题.这是一个演示我遇到的问题的示例程序: program test;{$APPTYPE CONSOLE}uses SysUtils, Windows, Dialogs;type TBlah = class public fe: Intege
program test;
{$APPTYPE CONSOLE}
uses
SysUtils, Windows, Dialogs;
type
TBlah = class
public
fe: Integer;
end;
function ThreadProc(param: Pointer) : DWORD;
begin
ShowMessage(IntToStr(TBlah(param).fe));
Result := 0;
end;
var
tID: DWORD;
handle: THandle;
b: TBlah;
begin
b := TBlah.Create;
b.fe := 54;
handle := CreateThread(nil, 0, @ThreadProc, Pointer(b), 0, tID);
WaitForSingleObject(handle, INFINITE);
end.
对ShowMessage的调用会弹出一个消息框,里面有245729105,而不像我期望的那样.
这可能只是对Delphi如何工作的基本误解,所以有人可以告诉我如何使其正常工作吗?
这里的问题是你的线程函数有错误的调用约定.您需要使用stdcall约定声明它:function ThreadProc(param: Pointer) : DWORD; stdcall;
话虽如此,仅仅使用一个TThread后代处理OOP到C函数回到OOP过渡会更加惯用.这看起来像这样:
type
TBlah = class(TThread)
protected
procedure Execute; override;
public
fe: Integer;
end;
procedure TBlah.Execute;
begin
ShowMessage(IntToStr(fe));
end;
var
b: TBlah;
begin
b := TBlah.Create(True);
b.fe := 42;
b.Start;
b.WaitFor;
end.
顺便说一下,有谁知道为什么Windows.pas将TFNThreadStartRoutine声明为TFarProc而不是正确的类型函数指针?
