I'm currently using Jint (https://github.com/sebastienros/jint) to process JavaScript.
I would like to be able to use a custom function in JavaScript that will execute a function created in C# and then return a value to the JavaScript.
For example if the JavaScript was:
var x = MultiplyByTwo(100);
And in my C# I had:
private static int MultiplyByTwo(int obj)
{
return obj * 2;
}
Then the above would give the variable x the value of 200.
According to the Documentation there is the following option:
var engine = new Engine()
.SetValue("log", new Action<object>(Console.WriteLine));
engine.Execute(@"
function hello() {
log('Hello World');
};
hello();
");
I can replace the "Console.Writeline" with a function name but it will only accept a void function. In other words, this can call a C# function from JS but not return a value.
Does an option like what I am looking for exist in Jint?
CodePudding user response:
As mentioned in some comments, use
SetValue("multiplyByTwo", new Func<int>(MultiplyByTwo))
CodePudding user response:
You can certainly reference a class, which can involve setting properties, and methods can return values. For example:
class Program
{
static void Main(string[] args)
{
var myobj = new MyClass();
var engine = new Engine()
.SetValue("log", new Action<object>(Console.WriteLine))
.SetValue("myobj", myobj);
engine.Execute(@"
function hello() {
myobj.One = 'asdf';
var x = myobj.TwoTimes(4);
log(x); // logs 8
};
hello();
");
Console.WriteLine($"{myobj.One}, {myobj.Two}");
// output => "asdf 8"
}
}
public class MyClass
{
public string One { get; set; }
public int Two { get; set; }
public int TwoTimes(int value)
{
Two = 2 * value;
return Two;
}
}
CodePudding user response:
Here is a fully functional example. Casting Console.WriteLine
is required since there are multiple overloads and we need to tell the compiler which one to use:
using System;
using Jint;
var engine = new Engine()
.SetValue("multiplyByTwo", MultiplyByTwo)
.SetValue("log", (Action<string>)Console.WriteLine)
;
engine.Execute(@"
var x = multiplyByTwo(3);
log(x);
");
static int MultiplyByTwo(int obj)
{
return obj * 2;
}