Passing the CreateThread parameter

I'm having a problem passing a class reference as a ThreadProc parameter in a call to CreateThread. Here is an example program that demonstrates the problem I am facing:

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.

The call ShowMessagebrings up a message box in which there is something like 245729105, and not 54, as I expect.

This is probably just a basic misunderstanding of how Delphi works, so can someone tell me how to do it right?

+3
source share
3 answers

The problem is that your thread function has the wrong calling convention. You must declare it using an agreement stdcall:

function ThreadProc(param: Pointer) : DWORD; stdcall;

enter image description here


, TThread, OOP to 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 ?

+9

stdcall.

function ThreadProc(param: Pointer) : DWORD; stdcall;
+9

And do not use Pointerin:

handle := CreateThread(nil, 0, @ThreadProc, **Pointer**(b), 0, tID); 

balready have Pointer(a Classwhich is Object Pointer)

+1
source

Source: https://habr.com/ru/post/1794557/


All Articles