Question

How can I call a procedure from a class that is created in main Form. Can it be done like this pseudo code shows?

type
  TDemo = class
    procedure test;
    constructor Create;
    destructor Destroy; override;
  end;

var
  Form28: TForm28;
  Demo:TDemo;

implementation

{$R *.dfm}

procedure TForm28.Button1Click(Sender: TObject);
var
   prog : IdwsProgram;
   exec : IdwsProgramExecution;
begin
   Demo := TDemo.Create;
   prog := DelphiWebScript1.Compile('Demo.Test;');
   exec := prog.Execute;
end;
Was it helpful?

Solution 2

To do this, you first have to expose your native class to the script engine. Have a look at the TdwsUnit component. It declares a script unit that interfaces with external code. You'd drop one on your form, define the class, define its methods, and hook up event handlers on the OnEval events that call the external routines.

OTHER TIPS

There is a limited RTTI exposer and RTTI connector, which allow to access Delphi classes through RTTI.

These RTTI tools haven't been explored much however, as most of the Delphi classes are not "safe" to use for scripting. By that I mean that it's easy to crash the host or leak memory, and so "raw" Delphi classes are typically unsuitable for end-user scripting (ie. end users won't have a right to error, you won't be able to offer stable debugging, etc.).

An alternative to manual exposure and strengthening of the exposed classes in event handlers of a TdwsUnit is to expose your classes as OLE Automation objects, and then you can use the DWScript COM Connector to access them. Then benefits is that to expose the automation objects, you'll usually have had to do at least minimal strengthening vs memory leaks and dangling pointers, and your automation classes will be accessible from other COM-capable environments.

As an example of RTTI going wrong, consider a fully automatically-managed VCL classes like TComponent or TCollection, if you only have raw RTTI exposure, than a script doing something like:

item := myCollection.Add;
myCollection.Clear;
item.Caption := 'hello bug';

will result in a random memory overwrite in the host application, without any safe ways to notify the script user about the potential error.

The upcoming Delphi ARC compilers may offer a way to mitigate the memory overwrites for some classes (though not all, due to the way ARC is currently implemented/circumvented for TComponent and others). Also Delphi ARC compilers are currently unsupported (for a variety of reasons, the most prominent one being I currently don't have access to them).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top