Jump to content
dormky

Cannot pass a procedure to another

Recommended Posts

Consider :

 

program ProjectThreadProc;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.Classes,
  Winapi.Windows;

type
  TMyRecord = class
    data: Integer;

    class procedure Queue(const AThread: TThread; AMethod: TThreadMethod);
  end;
  
class procedure TMyRecord.Queue(const AThread: TThread; AMethod: TThreadMethod);
begin
  OutputDebugString(PChar('In TMyRecord.Queue'))
end;

begin
  TThread.Queue(nil, procedure begin OutputDebugString(PChar('Hello !')) end);
  TMyRecord.Queue(nil, procedure begin OutputDebugString(PChar('Hello !')) end);
end.

This will give you, under 10.3 : [dcc32 Error] ProjectThreadProc.dpr(25): E2010 Incompatible types: 'TThreadMethod' and 'Procedure'

 

Notice that the line for TThread has no problems, and this compiles if you comment the call to TMyRecord.Queue. Problem is, on the face of it those two functions have the exact same signature :

image.thumb.png.0903897e739cbe5ca57616b350222b34.png

 

So why does TMyRecord.Queue not compile ? I'm baffled.

 

The end goal here is to pass an anonymous function to a thread, to be executed there.

Share this post


Link to post
program Project1;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.Classes,
  Winapi.Windows;

type
  TMyRecord = class
    data: Integer;

    class procedure Queue(const AThread: TThread; AMethod: TThreadProcedure);
  end;

class procedure TMyRecord.Queue(const AThread: TThread; AMethod: TThreadProcedure);
begin
  OutputDebugString(PChar('In TMyRecord.Queue'))
end;

begin
  TThread.Queue(nil, procedure begin OutputDebugString(PChar('Hello !')) end);
  TMyRecord.Queue(nil, procedure begin OutputDebugString(PChar('Hello !')) end);
end.

It should be TThreadProcedure not method.

  • Like 1

Share this post


Link to post

Here I was sitting and wondering how the hell it was compiling TThread when it should be TThreadProcedure for it too... Before noticing the overload beneath the function Delphi navigated to. God bless Delphi's function navigation, somehow worse at it than Christopher Colomb.

 

Good job noticing this !

Share this post


Link to post

In general, RTL types named TXXXMethod refer to non-static class methods, and TXXXProcedure types refer to anonymous procedures.

Share this post


Link to post

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×