tdwsUnit 声明一个 TObject 类型的属性,以及一个 getter 和一个 setter。实例化的对象应存储在 Delphi 端的“对象存储”中。目标是将对象从脚本 A 传输到脚本 B,其中脚本 A 在运行时在 Delphi 端创建并存储对象,而脚本 B 在运行时(同一 Delphi 进程)应从 Delphi 端读取对象并使用它。
Var ObjectStore : TObject;
procedure TDWSLibTools.TApp_GetObject(Info: TProgramInfo; ExtObject: TObject);
begin
// How to return object in ObjectStore?
<ResultOfThisGetter> := ObjectStore;
end;
procedure TDWSLibTools.TApp_SetObject(Info: TProgramInfo; ExtObject: TObject);
begin
// How to access the object in parameter named "Value"?
ObjectStore := Info.Vars['Value'].Get?????
end;
并且:即使正确完成,对象会在脚本运行之间“生存”吗?
您可以将任何 Delphi 对象实例公开给任何脚本,因此在一个脚本中创建 Delphi 对象并从另一个脚本访问该对象应该不会有问题。
听起来您的对象最初是从脚本创建的。我假设这个对象是在 Delphi 端声明的,然后类类型以某种方式暴露给脚本 - 例如通过
TdwsUnit
组件。
例如,在 Delphi 端,您声明了
TDelphiClass
,并且有一个名为 TScriptClass
的相应脚本类。我进一步假设您已经声明了一个带有 Object 属性的 TApp 脚本类(例如在 TdwsUnit
中),因此脚本端 API 看起来像这样:
type
TApp = class
protected
function GetObject: TScriptClass;
procedure SetObject(Value: TScriptClass);
public
property Object: TScriptClass read GetObject write SetObject;
end;
现在,据我所知,您只是问如何在 Delphi 端实现
GetObject
和 SetObject
TdwsUnit
事件处理程序。在下面的示例中,我假设您的 ObjectStore
变量属于 TDelphiClass
类型(以使我引用它的位置更加明显):
var
ObjectStore: TDelphiClass;
// TScriptClass.Create
procedure TDataModuleScript.dwsUnitStuffClassesTScriptClassConstructorsCreateEval(
Info: TProgramInfo; var ExtObject: TObject);
begin
if (ExtObject = nil) then
ExtObject := TDelphiClass.Create;
end;
// TApp.GetObject: TScriptObject
procedure TDataModuleScript.dwsUnitStuffClassesTAppMethodsGetObjectEval(
Info: TProgramInfo; ExtObject: TObject);
var
ClassSym: TClassSymbol;
ScriptObj: IScriptObj;
begin
// Get the script side class type
ClassSym := TClassSymbol(Info.FindSymbolInUnits('TScriptClass'));
if (ClassSym <> nil) then
begin
// We're not using the TApp Delphi side object here, but if
// there is one then ExtObject would point to it.
// Create a script side object to represent the Delphi side object
ScriptObj := TScriptObjInstance.Create(ClassSym, Info.Execution);
// Store a reference to the Delphi side object inside the
// script side object
ScriptObj.ExternalObject := ObjectStore;
// Return the script side object
Info.ResultAsVariant := ScriptObj;
end;
end;
// TApp.SetObject(Value: TScriptObject)
procedure TDataModuleScript.dwsUnitStuffClassesTAppMethodsSetObjectEval(
Info: TProgramInfo; ExtObject: TObject);
var
ParamInfo: IInfo;
ExtObj: TDelphiClass;
begin
// Get the parameter value
ParamInfo := Info.Vars['Value'];
if (ParamInfo.ValueIsEmpty) then
// parameter is nil
ExtObj := nil
else
// Parameter is object.
// Get the Delphi side reference and case to correct
// type (with type check)
ExtObj := ParamInfo.ExternalObject as TDelphiClass;
// Stash the reference to the Delphi side object
ObjectStore := TDelphiClass(ExtObj);
end;