[fpc-pascal] Assigning class method to procedure of object via class name in delphi mode

cobines cobines at gmail.com
Mon Jan 25 20:50:55 CET 2010


Hi,

I usually use objfpc mode, however I have a few units in delphi mode
and don't know if it is a bug or normal delphi behaviour.

In the following program I have variable of type "procedure of
object". If I assign a method of a class using object name:

  CM.Callback := CM.ContextMenuSelect;

everything is ok. But I can also assign it using class name:

  CM.Callback := TContextMenu.ContextMenuSelect;

The program obviously crashes with access violation in
ContextMenuSelect on access to FFiles.

Shouldn't this give a compilation error, or is it considered a programmer error?

_______

program class_callback;

{$mode delphi}{$H+}

uses
  Classes;

type
  TNotifyProc = procedure (Sender: TObject) of object;

  TContextMenu = class
  private
    FFiles: TStringList;
  public
    Callback: TNotifyProc;
    constructor Create;
    procedure ContextMenuSelect(Sender:TObject);
  end;

constructor TContextMenu.Create;
begin
  FFiles := TStringList.Create;
  FFiles.Add('Example string');
end;

procedure TContextMenu.ContextMenuSelect(Sender:TObject);
begin
  Writeln(FFiles[0]);
end;

var
  CM: TContextMenu;
begin
  CM := TContextMenu.Create;

  // This works fine
  CM.Callback := CM.ContextMenuSelect;
  CM.Callback(CM);

  // This causes crash
  // Should this be allowed to assign?
  CM.Callback := TContextMenu.ContextMenuSelect;
  CM.Callback(CM);

  CM.free;
end.

--
cobines



More information about the fpc-pascal mailing list