Using javascript for custom purposes

大兔子大兔子 提交于 2019-11-26 10:01:30

问题


I am writing a raytracer as a part of my complete 3d engine. I am planning on using javascript for the scripting language instead of writing my own. The question is how can I use it? Btw the raytracer and the UI are written in C#.


回答1:


This shows the two-way interaction between Javascript and c#.

  1. Javascript calls a c# method
  2. C# gets the result of an expression in Javascript

-

Type scriptType = Type.GetTypeFromCLSID(Guid.Parse("0E59F1D5-1FBE-11D0-8FF2-00A0D10038BC"));

dynamic obj = Activator.CreateInstance(scriptType, false);
obj.Language = "javascript";
obj.AddObject("MyClass",new JSAccessibleClass());

obj.Eval("MyClass.MsgBox('Hello World')"); //<--1
var result = obj.Eval("3+5"); //<--2


[ComVisible(true)]
public class JSAccessibleClass
{
    public void MsgBox(string s)
    {
        MessageBox.Show(s);
    }
}



回答2:


There are many standalone implementations of JavaScript that you may be able to leverage for this purpose:

Here is a link to the stackoverflow info page on JavaScript which lists at the top many of these implementations: https://stackoverflow.com/tags/javascript/info




回答3:


While it is possible to use JavaScript as scripting for .Net application it is not most popular choice. If you can pick other language - IronPython or LUA.Net may be choices you'll get better support. I listed several links in similar question recently: Write npc scripts to be executed by c# using class with npc methods.

Otherwise JavaScript.Net (part of .Net framework) or other implementations either explicitly .Net or with .Net bindings will work as scripting language.



来源:https://stackoverflow.com/questions/12118077/using-javascript-for-custom-purposes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!