Reputation:
I have been consuming a webservice with a javascript library and accessing the webservice via ExternalInterface calls back and forth from C# to Javascript and vice-versa. I no longer want to do this and am almost finished re-writing the library in C#. Most of it is working fine.
Unfortunately, there are a series of (static) methods in the javascript that I am finding very, very difficult to replicate in C#. Methods that have operators like this, for example:
static LongEmul dCb (LongEmul b) {
var c = ~b.l + 1 & 4194303;
var d = ~b.m + (c == 0 ? 1 : 0) & 4194303;
var e = ~b.h + (c == 0 && d == 0 ? 1 : 0) & 1048575;
return tBb(c, d, e);
}
This is my attempt at refactoring the javascript: not very good. How can I create some kind of DOM or Javascript parser object on startup, write the javascript methods or full class to this object, and then call methods in the object with parameters from c# and receive return values back. I know this sounds a bit like the ExternalInterface approach I'm replacing, but I'm intrigued to find out if a method in Javascript syntax can be called from C# in any way.
I'd appreciate any help at all with this.
Thanks.
Upvotes: 3
Views: 214
Reputation: 2141
You may want to use Jint, a JavaScript interpreter for .NET. Jint allows you to feed it with some JavaScript code and not only interprets it, but even lets you call JS methods directly from your .NET code.
From the Jint website:
script= @"
function square(x) {
return x * x;
};
return square(number);
";
var result = new JintEngine()
.SetParameter("number", 3)
.Run(script));
Assert.AreEqual(9, result);
Calling a specific JS method (from the docs):
JintEngine jint = new JintEngine();
jint .Run(@"
var f = function (x, y) {
return x * y;
}
";
Console.WriteLine(jint.CallFunction("f", 2, 3)); // Displays 6
Upvotes: 1