Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!"
  • 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?
like image 285
Mohamed ElHamamsy Avatar asked Jun 28 '26 12:06

Mohamed ElHamamsy


1 Answers

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.

like image 137
Sébastien Ros - MSFT Avatar answered Jul 01 '26 00:07

Sébastien Ros - MSFT



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!