delphidwscript

DWScript: exposing and returning an object to script from Delphi function?


In my Delphi (2010) code I have a class TImageItem, which I have exposed to DWScript via:

dwsUnit.ExposeRTTI(TypeInfo(TImageItem),[eoNoFreeOnCleanup, eoExposePublic]);

In dwsUnit I have declared a function to get a TImageItem from the Delphi side:

function GetImage: TImageItem;

and on the Delphi side:

procedure TFScript.dwsUnitFunctionsGetImageEval(info: TProgramInfo);
begin
    ...
    // (Item is a TImageItem and not nil)
    Info.ResultAsVariant := TdwsRTTIVariant.FromObject(Item);
end;

However, when I run a script starting like:

var Item: TImageItem;
Item := GetImage;
...

I get an EScriptError during the GetImage call with the message "Object already destroyed".

What am I doing wrong? Am I exposing the object or returning it incorrectly?


Solution

  • I don't know about ExposeRTTI, as I've never used it, but I would do it like this:

    procedure TFScript.dwsUnitFunctionsGetImageEval(info: TProgramInfo);
    begin
      ...
      // (Item is a TImageItem and not nil)
      Info.ResultAsVariant := Info.Vars[Info.ResultVars.TypeSym.Name].GetConstructor('Create', Item).Call.Value;
    end;