0

I'm trying creating a TAction in runtime and insert in TActionClientItem, but it's give me an error at runtime (Invalid class typecast).
I'm using this way:

function TFunctions.AddMenuItem(aciParent: TActionClientItem): integer;
var
  ClientItem: TActionClientItem;
  ActionToAdd: TAction;
begin
  ClientItem:= aciParent.items.add;
  ClientItem.Action := ActionToAdd; // <- error
  //
end;
Uli Gerhardt
  • 13,748
  • 1
  • 45
  • 83
  • What error - compiler or runtime error? Paste an exact copy of the error message. Which Delphi version? – Uli Gerhardt Aug 11 '22 at 13:45
  • runtime error. the message is "Invalid class typecast". I'm use Delphi 10.2 – Kaue Barros Aug 11 '22 at 19:24
  • Then enable "Debug DCUs" in the project options, rebuild, run and hit "Break" when the exception box pops up. – Uli Gerhardt Aug 12 '22 at 06:36
  • I did try this, but this function is inside in dll and when is execute the application in "Host application", the message is showed and when i click in "Break" is open a .pas of the application instead .pas in dll – Kaue Barros Aug 13 '22 at 19:33
  • The DLL thing is crucial. You probably have to use a [package](https://docwiki.embarcadero.com/RADStudio/Alexandria/en/Packages_(Delphi)) instead if you want to make this work. – Uli Gerhardt Aug 15 '22 at 07:37

2 Answers2

0

Should mark the code block above as code so that it gets formatted properly (or at least as a preformatted block). Where is the "begin" statement? After the var block with the local variables declarations (you have two of those, ClientItem and ActionToAdd) there should be a "begin" statement and then your imperative commands, then have "end" statement to close the function declaration.

The error is from the parsing stage if "begin" is missing, but I'd expect it to be at ClientItem:= aciParent.items.add; (at the := point)

Obviously before "end" should also assign the "result" variable or can also return a result passing it as parameter to the "exit" statement if you need to have multiple exit points from your function. Use procedure instead of function if no result needed

George Birbilis
  • 2,782
  • 2
  • 33
  • 35
  • Sorry, i'm not paste all the block, but "begin" and "end" exist. It´s block is a function, but i will change it. – Kaue Barros Aug 11 '22 at 13:54
0

You mentioned in a comment that your code lives in a DLL. DLLs have their own copy of the VCL distinct from the one in the executable and mixing objects from different VCL instances doesn't work. You should switch to a package instead. These are built to handle these issues.

Uli Gerhardt
  • 13,748
  • 1
  • 45
  • 83