如何在PascalScript中注册自定义数据类型TCallback?
Hey there, since you already have experience registering functions and classes in PascalScript, adding your TCallback procedure type is a smooth next step! Let's walk through how to do it alongside your existing code, plus how to use the type in scripts.
Step 1: Register the Type in the ExecImport Event
In your existing PSScript1ExecImport handler, add a line to register the TCallback type using RegisterDelphiType. This maps your Delphi-side type definition to a name the script engine can recognize.
procedure TForm1.PSScript1ExecImport(Sender: TObject; se: TPSExec; x: TPSRuntimeClassImporter); type TCallback = procedure; // Match your global type definition here begin // Your existing custom function registration se.RegisterDelphiFunction(@MWrites, 'Writes', cdRegister); // Your existing custom class registration var CustomClass: TPSRuntimeClass; CustomClass := x.Add(TPerson); CustomClass.RegisterMethod(@TPerson.setAge, 'setAge'); // Register the TCallback procedure type se.RegisterDelphiType(TypeInfo(TCallback), 'TCallback'); end;
Quick Breakdown:
TypeInfo(TCallback)pulls the runtime type metadata for your Delphi procedure type.- The second parameter (
'TCallback') is the name scripts will use to reference this type—stick to your Delphi naming for consistency.
Step 2: Use TCallback in Your PascalScript
Once registered, you can declare TCallback variables in scripts, assign procedures to them, and invoke them just like you would in Delphi:
var MyCallback: TCallback; procedure ScriptSideProcedure; begin Writes('Callback triggered from the script!'); end; begin // Assign a script-defined procedure to the callback variable MyCallback := @ScriptSideProcedure; // Execute the callback MyCallback(); end;
Pro Tip for Extended Callback Types
If you later update TCallback to include parameters (e.g., type TCallback = procedure(StatusMsg: string);), the registration process stays identical—just make sure your script-side procedures match the exact parameter signature of the Delphi type to avoid compatibility errors.
内容的提问来源于stack exchange,提问作者Tom

