3

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!"
  • I can't understand what happens in background? Which compiler will compile the injected c# code in JS file? C# Compiler or JS?
  • If I declared C# List in JS file, Is the generated object JS object or C# object?
sepp2k
  • 363,768
  • 54
  • 674
  • 675

2 Answers2

1

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.

Sébastien Ros - MSFT
  • 5,091
  • 29
  • 31
0

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.
Christoph
  • 2,211
  • 1
  • 16
  • 28