Mohamed ElHamamsy
Mohamed ElHamamsy

Reputation: 221

What happens if I define a .Net class in JavaScript code using Jint engine

In Jint, you can access .Net classes in JS.

JS File Code :

var write = function (msg) {

    var log = System.Console.WriteLine;
    log(msg);
};

C# Code

 Engine jsEngine = new Engine(e=>e.AllowClr());
 string script = System.IO.File.ReadAllText("file1.js");
 jsEngine.Execute(script);
 jsEngine.Invoke("write", "Hello World!");  //Displays in Console: "Hello World!"

Upvotes: 3

Views: 1350

Answers (2)

Christoph
Christoph

Reputation: 2317

Let's walk through the Invoke call step by step:

  1. jsEngine.Invoke causes Jint to execute the write method, in JavaScript, and passes in "Hello World!"
  2. the write method calls System.Console.WriteLine, at which point Jint transitions out of JavaScript back to managed code and calls that method.

Now to your questions:

  1. No code gets injected. Your code only transitions from managed into script (interpreted) into managed execution.
  2. If you create a C# List object in JS, the object is a real managed .Net object.

Upvotes: 0

You are not injecting C# code, the Jint interpreter will understand that you are reference to a .NET class, and hence execute this code. Because Jint is written in .NET it can run any .NET code you are asking.

Also Jint doesn't compile anything, it reads every javascript statement and tries to evaluate them one after the other, keeping track of all variables, functions and other JS artifacts your are declaring and using.

Upvotes: 1

Related Questions