besen icon indicating copy to clipboard operation
besen copied to clipboard

NativeObject string properties

Open lazuser opened this issue 9 years ago • 3 comments

Hi Benjamin! BESEN does not see native object's string properties. Or maybe I did something wrong?

program BESENTest;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils,
  BESEN,
  BESENValue,
  BESENObject,
  BESENConstants,
  BESENNativeObject;

type
  TScriptSys = class
  public
    procedure print(const ThisArgument: TBESENValue; Arguments: PPBESENValues; CountArguments: integer; var AResult:TBESENValue);
  end;

  TTestClass = class(TBESENNativeObject)
  private
    fTestKey: String;
  protected
    procedure ConstructObject(const ThisArgument: TBESENValue; Arguments: PPBESENValues; CountArguments: integer); Override;
  public
    constructor Create(AInstance: TObject; APrototype: TBESENObject=nil; AHasPrototypeProperty: longbool=false); Overload; Override;
  published
    property testKey: String read fTestKey;
  end;

var
  BesenInst: TBesen;
  ScriptSys: TScriptSys;

procedure TScriptSys.print(const ThisArgument: TBESENValue; Arguments: PPBESENValues; CountArguments: Integer; var AResult: TBESENValue);
begin
  writeLn(TBESEN(BesenInst).ToStr(Arguments^[0]^));
end;

constructor TTestClass.Create(AInstance: TObject; APrototype: TBESENObject=nil; AHasPrototypeProperty: longbool=false);
begin
  inherited Create(AInstance, APrototype, AHasPrototypeProperty);
  fTestKey := 'test string value';
end;

procedure TTestClass.ConstructObject(const ThisArgument: TBESENValue; Arguments: PPBESENValues; CountArguments: integer);
begin
  inherited ConstructObject(ThisArgument, Arguments, CountArguments);
end;

begin
  BesenInst := TBesen.Create(COMPAT_JS);
  ScriptSys := TScriptSys.Create;
  BesenInst.ObjectGlobal.RegisterNativeFunction('print', ScriptSys.Print, 1, []);
  BesenInst.RegisterNativeObject('Test', TTestClass);
  BesenInst.Execute(
    'var obj = new Test();' +
    'print(obj.testKey);' +
    'print(JSON.stringify(obj));'
  );
  readLn;
end.

lazuser avatar Jun 21 '16 15:06 lazuser

It works for me, i tried a string and integer property, it seems to work well, but property has to be published, which seems you did correct, maybe you need to re-test as this could be something that bero fixed?

Also, which compiler did you use? i used this in delphi 7 and it worked all ok.

JernejL avatar Feb 13 '18 07:02 JernejL

@lazuser - Make sure {$M+} is enabled in your code... which turns on RTTI so the code can crawl the published properties. Otherwise, they are optimized out... ( I know this is 4 yr old question, but n00bs may hit this).

3FLLC avatar Sep 28 '20 14:09 3FLLC

I suppose {$typeInfo on} is same.

Bero could fix this by extending TBESENBaseObject from Tpersistent instead from TObject ( https://www.freepascal.org/docs-html/rtl/classes/tpersistent.html ) which is always in {$M+}

JernejL avatar Oct 02 '20 07:10 JernejL