dmeier
dmeier

Reputation: 41

delphi: send a class via postmessage in 64 Bit

I would like to make my application 64 Bit compatible. I'm struggling with PostMessage and LPARAM. I send an instance of a class via PostMessage. I wonder if it's correct to cast the value test_data to LPARAM.

Please have a look at the following code:

// Data to send 
TMyData=class
  Data1: string;
  Data2: byte;
  Data3: TDateTime;
end;

// send
procedure TTestClass1.PostTestData(AData1: string; AData2: byte; AData3: TDateTime);
var
  test_data: TMyData;
begin
  test_data:= TMyData.Create;

  test_data.Data1:= AData1;
  test_data.Data2:= AData2;
  test_data.Data3:= AData3;

  PostMessage(my_handle,WM_MY_MESSAGE,0,LPARAM(test_data));
end;


// receive
procedure TTestClass2.Message_WM_MY_MESSAGE(var Msg: TMessage);
var
  test_data: TMyData;
begin
  test_data := TMyData(Msg.LParam); // is this also compatible with 64 Bit?

  try
    // Do some work
  finally
    test_data.Free;
  end;
end;

Is the code above 64 Bit compatible?

Upvotes: 2

Views: 1156

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 595772

What you have shown will work just fine, as LPARAM is defined as LONG_PTR, which is a pointer-sized integer on both 32bit and 64bit systems (same with WPARAM, which is defined as UINT_PTR). Many standard Win32 messages carry pointers in their WPARAM and LPARAM values. User-defined messages are allowed to do the same (as long as they do not cross process boundaries).

Just be sure to Free your object if PostMessage() fails, since Message_WM_MY_MESSAGE() will not be called in that situation:

procedure TTestClass1.PostTestData(AData1: string; AData2: byte; AData3: TDateTime);
var
  test_data: TMyData;
begin
  test_data := TMyData.Create;

  test_data.Data1 := AData1;
  test_data.Data2 := AData2;
  test_data.Data3 := AData3;

  if not PostMessage(my_handle, WM_MY_MESSAGE, 0, LPARAM(test_data)) then
    test_data.Free; // <-- add this
end;

Upvotes: 5

Related Questions