[SOLVED] Using global procedure as an event — invalid data in parameters lazarus / 62-General ---------------------------------------------------------------------- flowCRANE · 2022-02-26 17:32 I was curious to see if I can assign a normal global routine to some class event. I can't do it directly (because of types incompatibility), but there is a way to do it using magic with the TMethod type. I did something like this (that's all the test project code): Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i uses  Classes, SysUtils, Forms, Controls; type  TMainForm = class(TForm)    procedure FormCreate(ASender: TObject);  end; var  MainForm: TMainForm; implementation {$R *.lfm} procedure FormMouseMove(ASender: TObject; AShift: TShiftState; AX, AY: Integer);begin  TForm(ASender).Caption := 'X: %d, Y: %d'.Format([AX, AY]);end; procedure TMainForm.FormCreate(ASender: TObject);var  Method: TMethod;begin  Method.Data := Self;  Method.Code := @FormMouseMove;   OnMouseMove := TMouseMoveEvent(Method);end; end. It works. But the problem is that AX parameter always contains 0 and the AY parameter contains X coordinate. Can somebody explain why is this happening and what to do to make such a code works properly? I don't need to do something like this in any of my sirious projects, I'm just curious. ---------------------------------------------------------------------- winni · 2022-02-26 18:51 Hi! Some kind of parameter shift: In the AX-values there are the values of the shiftstate: Shift=1, Alt=2, Ctrl=4 ... And in the shiftstate there seems to be a constant. Change your MouseMove for testing to this: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i procedure FormMouseMove(ASender: TObject; AShift: TShiftState; AX, AY: Integer);var s : string = ' ';    tmp: string;shift : TShiftStateEnum;beginfor shift := low(TShiftStateEnum) to high (TShiftStateEnum) do   begin   if shift in Ashift then      begin    writeStr(tmp,shift);      s := s + tmp+' ';        end;  end;  TForm(ASender).Caption :=  'X: %d, Y: %d'.Format([AX, AY])  +s;end;         And press Ctrl, Shift, Alt ... while you move the mouse and look at the X-value. Strange, strange Winni ---------------------------------------------------------------------- flowCRANE · 2022-02-26 20:20 That's why I'm asking what's going on here. Memory alignment problem? ---------------------------------------------------------------------- howardpc · 2022-02-26 21:10 Not a memory alignment problem - a missing self parameter. Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i unit uMain; {$mode ObjFPC}{$H+} interface uses  Classes, SysUtils, Forms, Controls; type  TMainForm = class(TForm)    procedure FormCreate(Sender: TObject);  private    procvar: TMouseMoveEvent;  end; var  MainForm: TMainForm; implementation {$R *.lfm} function Shiftstate2Str(aShiftstate: TShiftState): String;var  shift: TShiftStateEnum;begin  Result := '[';  for shift in aShiftstate do    begin      case shift of        ssShift:  result := result + 'ssShift, ';        ssAlt:    result := result + 'ssAlt, ';        ssCtrl:   result := result + 'ssCtrl, ';        ssLeft:   result := result + 'ssLeft, ';        ssRight:  result := result + 'ssRight, ';        ssMiddle: result := result + 'ssMiddle, ';        ssDouble: result := result + 'ssDouble, ';        ssMeta:   result := result + 'ssMeta, ';        ssSuper:  result := result + 'ssSuper, ';        ssHyper:  result := result + 'ssHyper, ';        ssAltGr:  result := result + 'ssAltGr, ';        ssCaps:   result := result + 'ssCaps, ';        ssNum:    result := result + 'ssNum, ';        ssScroll: result := result + 'ssScroll, ';        ssTriple: result := result + 'ssTriple, ';        ssQuad:   result := result + 'ssQuad, ';        ssExtra1: result := result + 'ssExtra1, ';        ssExtra2: result := result + 'ssExtra2, ';      end;    end;  if Copy(Result, Length(Result)-1, 2) = ', ' then    Delete(Result, Length(Result)-1, 2);  Result := Result + ']';end; procedure FormMouseMove({%H-}aSelf: TObject; ASender: TObject; AShift: TShiftState; AX, AY: Integer);begin  TMainForm(ASender).Caption := 'X: %d, Y: %d AShift: %s'.Format([AX, AY, Shiftstate2Str(AShift)]);end; procedure TMainForm.FormCreate(Sender: TObject);begin  TMethod(procvar).Data := Self;  TMethod(procvar).Code := @FormMouseMove;  OnMouseMove := procvar;end; end. ---------------------------------------------------------------------- flowCRANE · 2022-02-26 21:46 Thanks @howardpc — it works properly now. But still, what this ASelf parameter mean? What is the difference between ASelf and ASender in this example? ---------------------------------------------------------------------- howardpc · 2022-02-26 21:55 Methods of a class look like standard non-class procedures and functions. However, by compiler sleight-of-hand all methods have a hidden Self parameter that is passed along with the other explicit parameters, which references the method's instance. This is what the "of object" postfix syntax ensures when you declare a new method type. It tells the compiler that this routine requires the hidden Self parameter, because it will be used in some class or other. It is hidden only from the programmer, and is obvious to the compiler. So when you construct a hack to make a "standard" procedure or function behave like a method, you have to supply the (normally hidden) parameter which  anchors the method to the correct class instance. No doubt a compiler developer can correct any misunderstanding of this on my part. ---------------------------------------------------------------------- Thaddy · 2022-02-27 07:38 The answer by howardpc is correct and well explained. In KOL there is even a MakeMethod as a helper function that does about the same: Take a TMethod record and implement self (often as just as a dummy in the case of KOL) Note a procedure of object can be global too and that can be assigned to class instances directly. Then again, if you call a procedure of object outside the context of a class or object, you will need to provide the dummy parameter, which is the hidden self as the leftmost parameter. So you will still need to set up a Tmethod for that on use. ---------------------------------------------------------------------- PascalDragon · 2022-02-27 10:43 Quote from: furious programming on February 26, 2022, 10:46:00 pmThanks @howardpc — it works properly now. But still, what this ASelf parameter mean? What is the difference between ASelf and ASender in this example? In addition to what howardpc and Thaddy wrote: the Self value inside a method doesn't just magically appear. The instance is always passed in as a hidden parameter (it might even be Nil) and thus the signature of a method is different from a global routine by having the hidden Self parameter. ---------------------------------------------------------------------- Warfley · 2022-02-27 11:14 The question is, is a method always equivalent with a function which has the first parameter as Self, and if so, is it documented? Because I always thought this is one of these undocumented things that a programmer should not rely upon because this might change in new compiler versions, different optimisation levels or even just with different function signatures. ---------------------------------------------------------------------- Thaddy · 2022-02-27 14:50 It IS documented in more than one place. https://www.freepascal.org/docs-html/ref/refsu30.html is just one example. Note a static class method has the same fingerprint as a normal procedure and does not know about self. That means that in that case they are interchangeable. ---------------------------------------------------------------------- Warfley · 2022-02-27 22:49 Where is it documented that a method is the same as a function with self as the first parameter? I checked your link it does not say anything like that. I checked all the subpages of Methods, as well as the procedural types page. Your link says "self parameter" exactly once, but only in that static parameters does not have one. What it does not describe is, for non statics, how it is passed, if it's the first, last, or third parameter and if it can be emulated using a normal function. From all I know FPC could add up to 27 hidden parameters of which self is passed as the 14th on mondays, 21st on full moon nights and in all other cases it is the rolling average CPU frequency over the runtime of the program modulo 27. Or maybe it is even different for procedures, functions or class procedures and class functions. If it is not documented, for all I know it could be implemented using magic. ---------------------------------------------------------------------- PascalDragon · 2022-02-28 14:02 Quote from: Warfley on February 27, 2022, 12:14:21 pmThe question is, is a method always equivalent with a function which has the first parameter as Self, and if so, is it documented? Because I always thought this is one of these undocumented things that a programmer should not rely upon because this might change in new compiler versions, different optimisation levels or even just with different function signatures. The ABI doesn't change with optimizations and it's also fixed between compiler versions (except a bug was found). It might be different between platforms or calling conventions (e.g. if a platform or calling convention denotes a specific register register as Self (like ECX in Microsoft's thiscall) then a global function would never put any of the parameters there). Main conflict inside the same platform/calling convention might be a hidden result parameter if the result value is passed through a hidden var-parameter instead of through the normal result register (e.g. managed types): it depends upon the ABI whether it's inserted first, after Self or last. So this might make it hard to impossible to declare a suitable global function.