javascriptc#jint

How do I return a value from a C# function using jint?


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?


Solution

  • 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;
    }