代码如下:
type  RTest=record
    stxt: string;
    rtxt: string;
  end;
  PTest = ^RTest;function testfunc(Param:PTest):integer;stdcall;begin
  form1.label1.caption:='test';
  result:=0;
end;procedure Tform1.Button1Click(Sender: TObject);
var
  TID: CARDINAL;
  Hthread: THandle;  P: Ptest;
begin
  new(p); 
  p.stxt:=memo2.Text;
  p.rtxt:=memo1.Text;
TRY
  Hthread:= BeginThread(nil, 1024, @testfunc, p, 0, TID);
FINALLY
  dispose(p);
END;
end;我用如上代码会出错,而这样定义testfunc,即去掉参数,就OK
function testfunc:integer;stdcall;
这是为什么啊?

解决方案 »

  1.   

    将 BeginThread -> CreateThread
      

  2.   

    我前面代码贴错了
     Hthread: THandle;应该是 Hthread: integer;
    ,我试了将1024改为0,也不行。
      

  3.   

    testfunc不是TThreadFunc类型。试试这样定义:
    function testfunc(Param: Pointer):integer;调用:
     Hthread:= BeginThread(nil, 1024, testfunc, Pointer(p), 0, TID);
      

  4.   

    首先,你的线程函数的定义有问题,这个4楼说了,就不重复了。
    其次是你参数传递的有问题
      new(p); 
      p.stxt:=memo2.Text;
      p.rtxt:=memo1.Text;
    TRY
      Hthread:= BeginThread(nil, 1024, @testfunc, p, 0, TID);
    FINALLY
      dispose(p);
    END;
    你 New了一个p,然后把这个指针传递给线程了,然后紧接着就 dispose(p) 
    因为线程函数的执行和 dispose(p) 是并列的,也就是说,线程中接受的这个指针p指向的内存被你释放了。
      

  5.   

    按4楼的定义
    按5楼的去掉了dispose(p); 仍然错误只要testfunc定义时带参数,就报错
      

  6.   

    unit Unit1;interfaceuses
      Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
      Dialogs, StdCtrls;type
      TForm1 = class(TForm)
        Button1: TButton;
        procedure Button1Click(Sender: TObject);
      private
        { Private declarations }
        procedure WMUser2(var Msg: TMessage); message WM_USER + 1234;
      public
        { Public declarations }
      end;var
      Form1: TForm1;implementation{$R *.dfm}type
      PThreadMsg = ^TThreadMsg;
      TThreadMsg = record
        Handle: HWND;
        Msg: String;
      end;function testfunc(Param: Pointer):integer;
    begin
      with PThreadMsg(Param)^ do
        SendMessage(Handle, WM_USER + 1234, 0, Integer(Msg));
      Dispose(PThreadMsg(Param));
    end;
    procedure TForm1.Button1Click(Sender: TObject);
    var
      TID: CARDINAL;
      p: PThreadMsg;
    begin
      New(p);
      p.Handle := self.Handle;
      p.Msg := '你好';
      BeginThread(nil, 1024, testfunc, Pointer(p), 0, TID)
    end;procedure TForm1.WMUser2(var Msg: TMessage);
    begin
      Caption := PChar(Msg.LParam);
    end;end.以上代码,在Delphi7 的默认配置下(就是安装完了不做任何配置),编译运行通过,点击按钮就,form1的caption 被设置成 "你好"
      

  7.   

    VCL的控件,不是线程安全的,因此,你不能再线程中直接操作窗体上的控件,也就是说,你线程中写的form1.label1.caption:='test'这句,是不安全的
      

  8.   

    BeginThread 下对变量等控制严格,所以用createthread可以传递参数的线程函数,不一定beginthread可以。调了好几天,才弄明白。