只是想知道是否有人尝试过将任何js引擎嵌入到。net环境中。我可以找到并实际使用(经过大量的痛苦和努力,因为它相当过时,还没有完全完成)spidermonkey-dotnet项目。有人有这方面的经验吗?引擎像SquirrelFish, V8..

并不是说我对Mozilla的Spidermonkey不满意(在核心ASP中使用它为自定义组件提供类似rails的迷你框架)。NET应用程序),但我仍然想进一步探索这些选项。命令行解决方案不是我所需要的,我不能依赖CLR以外的任何东西,我需要从/到JavaScript/ c#对象调用方法。

// c# class
public class A
{
    public string Hello(string msg)
    {
        return msg + " whatewer";
    }
}

// js snippet
var a = new A();
console.log(a.Hello('Call me')); // i have a console.log implemented, don't worry, it's not a client-side code :)

澄清一下——我并不是试图用服务器端javascript编写应用程序本身。它仅用于编写自定义用户子应用程序(可以看作某种DSL)。让普通人用js编程比用c#更容易(也更安全)。


当前回答

我相信所有主要的开源JS引擎(JavaScriptCore、SpiderMonkey、V8和KJS)都提供了嵌入api。我唯一真正熟悉的是JavaScriptCore(这是SquirrelFish所在的JS引擎的名称),它提供了一个纯C API。如果没记错的话(自从我使用。net已经有一段时间了)。net在C API中对链接提供了相当好的支持。

老实说,我不确定其他引擎的API是什么样的,但我知道它们都提供了API。

也就是说,这取决于你的目的。NET可能是最好的,因为所有这些其他引擎都需要你将它们包含在你的应用程序中,因为JSC是唯一一个实际附带操作系统的引擎,但这个操作系统是MacOS:D

其他回答

如果语言不是问题(任何沙盒脚本语言),那么。net有LUA。. net框架的Silverlight版本也是沙盒的。

我想出了一个更简单的办法。

我使用Javascript构建了一个.dll文件,然后使用VS2013开发人员命令提示符中提供的Javascript编译器编译它。

一旦我们有了。dll,我们只需将它添加到\Support文件夹,然后在需要评估Javascript语句的项目中引用它。

创建.dll的详细步骤:

Create a file in Notepad with only these contents: class EvalClass { function Evaluate(expression: String) { return eval(expression); } } Save the file as C:\MyEval.js Open a VS2005 Command Prompt (Start, Programs, VS2005, VS2005 Tools) Type Cd\ to get to C:\ Type jsc /t:library C:\MyEval.js A new file is created named MyEval.dll. Copy MyEval.dll to the project and reference it (also reference Microsoft.Jscript.dll). Then you should be able to call it like this: Dim jScriptEvaluator As New EvalClass Dim objResult As Object objResult = jScriptEvaluator.Evaluate(“1==1 && 2==2”)

objResult为True。

您可能也会对Microsoft ClearScript感兴趣 它托管在GitHub上,并在Ms-Pl许可下发布。

我不是微软的粉丝,但我必须承认V8支持的功能和Javascript差不多。Net,更重要的是,该项目仍在维护。就我而言,对委托的支持也比Spidermonkey-dotnet更好。

ps:它也支持JScript和VBScript,但我们对这个老东西不感兴趣。

ps:它兼容。net 4.0和4.5+

开源JavaScript解释器Jint (http://jint.codeplex.com)正是您想要的。

编辑: 该项目已经完全重写,现在托管在Github上https://github.com/sebastienros/jint

嘿,在codeplex (http://javascriptdotnet.codeplex.com/)上看看Javascript . net的0.3.1版本,有一些非常棒的新特性,你可能会感兴趣。

查看示例代码:

// Initialize the context
JavascriptContext context = new JavascriptContext();

// Setting the externals parameters of the context
context.SetParameter("console", new SystemConsole());
context.SetParameter("message", "Hello World !");
context.SetParameter("number", 1);

// Running the script
context.Run("var i; for (i = 0; i < 5; i++) console.Print(message + ' (' + i + ')'); number += i;");

// Getting a parameter
Console.WriteLine("number: " + context.GetParameter("number"));