Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to invoke a function written in a javascript file from C# using IronJS

Tags:

c#

ironjs

I just download the Iron JS and after doing some 2/3 simple programs using the Execute method, I am looking into the ExecuteFile method.

I have a Test.js file whose content is as under

function Add(a,b)
{
    var result = a+b;
    return result;
}

I want to invoke the same from C# using Iron JS. How can I do so? My code so far

var o = new IronJS.Hosting.CSharp.Context();
dynamic loadFile = o.ExecuteFile(@"d:\test.js");
var result = loadFile.Add(10, 20);

But loadfile variable is null (path is correct)..

How to invoke JS function ,please help... Also searching in google yielded no help.

Thanks

like image 799
learner123 Avatar asked Aug 30 '11 07:08

learner123


1 Answers

The result of the execution is going to be null, because your script does not return anything.

However, you can access the "globals" object after the script has run to grab the function.

var o = new IronJS.Hosting.CSharp.Context();
o.ExecuteFile(@"d:\test.js");
dynamic globals = o.Globals;

var result = globals.Add(10, 20);

EDIT: That particular version will work with the current master branch, and in an up-coming release, but is not quite what we have working with the NuGet package. The slightly more verbose version that works with IronJS version 0.2.0.1 is:

var o = new IronJS.Hosting.CSharp.Context();
o.ExecuteFile(@"d:\test.js");
var add = o.Globals.GetT<FunctionObject>("Add");

var result = add.Call(o.Globals, 10D, 20D).Unbox<double>();
like image 92
John Gietzen Avatar answered Oct 05 '22 23:10

John Gietzen