Javascript Interpreter for C# (no dependencies)
#scripting #script-engine
|
11 years ago | |
---|---|---|
.nuget | 11 years ago | |
Jint | 11 years ago | |
Jint.Benchmark | 11 years ago | |
Jint.Repl | 11 years ago | |
Jint.Tests | 11 years ago | |
Jint.Tests.CommonScripts | 11 years ago | |
Jint.Tests.Ecma | 11 years ago | |
Jint.Tests.Scaffolding | 12 years ago | |
.gitignore | 12 years ago | |
CREDITS.txt | 11 years ago | |
Jint.sln | 11 years ago | |
Jint.sln.DotSettings | 11 years ago | |
LICENSE.txt | 11 years ago | |
README.md | 11 years ago |
Jint is a Javascript interpreter for .NET. Jint doesn't compile Javascript to .NET bytecode and in this sense might be best suited for projects requiring to run relatively small scripts faster, or which need to run on different platforms.
This example defines a new value named log
pointing to Console.WriteLine
, then executes
a script calling log('Hello World!')
.
var engine = new Engine()
.SetValue("log", new Action<object>(Console.WriteLine))
;
engine.Execute(@"
function hello() {
log("Hello World");
};
hello();
");
Here, the variable x
is set to 3
and x * x
is executed in JavaScript. The result is returned to .NET directly, in this case as a double
value 9
.
var square = new Engine()
.SetValue("x", 3) // define a new variable
.Execute("x * x") // execute a statement
.GetCompletionValue() // get the latest statement completion value
.ToObject() // converts the value to .NET
;
You can also directly pass POCOs or anonymous objects and use them from JavaScript. In this example for instance a new Person
instance is manipulated from JavaScript.
var p = new Person {
Name = "Mickey Mouse"
};
var engine = new Engine()
.SetValue("p", p)
.Execute("p.Name === 'Mickey Mouse')
;
If you need to pass a JavaScript callback to the CLR, then it will be converted to a Delegate
. You can also use it as a parameter of a CLR method from JavaScript.
var function = new Engine()
.Execute("function add(a, b) { return this + a + b; }");
.GetGlobalValue("add")
.ToObject() as Delegate;
var result = function.DynamicInvoke(
new JsValue("foo") /* thisArg */,
new JsValue[] { 1, "bar" } /* arguments */,
); // "foo1bar"
IDictionary<string, object>
and dynamic)