You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在PascalScript中注册自定义数据类型TCallback?

Registering a Custom Procedure Type (TCallback) in PascalScript

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 10:57:29