C# 底下 的 javascript(JS) 直譯器 (interpreter) [CS_test_jint project]

C# 底下 的 javascript(JS) 直譯器 (interpreter) [CS_test_jint project]

C# 底下 的 javascript(JS)  直譯器 (interpreter) [CS_test_jint project]


資料來源:

https://github.com/sebastienros/jint
https://www.youtube.com/watch?v=yCs6UmogKEg&t=57s
https://docs.microsoft.com/zh-tw/shows/code-conversations/sebastien-ros-on-jint-javascript-interpreter-net

https://blog.no2don.com/2020/03/cnet-core-c-jint-javascript.html


GITHUB: https://github.com/jash-git/CS_test_jint-project


官方教學影片備份



Code

    01.JS

//https://blog.no2don.com/2020/03/cnet-core-c-jint-javascript.html
function JSCallJS(a, b) {
    return "" + (GetSum(a, b) + 10);
}
//-----------

function GetSum(a, b) {
    return a + b;
}


function Echo() {
    return str + " From Javascript";
}

function CallServerFunc(name) {
    return name + " From Javascript - CallServerFunc";
}

function CallServerFunc2(name) {
    return testapi.GetStringFromClassFunction(name) + " From Javascript - CallServerFunc";

}

function parseJson() {
    obj = JSON.parse(json_data);

    var data = '';
    for (var i = 0; i < obj.sites.length; i++) {
        data += obj.sites[i].name + " : " + obj.sites[i].url+"\n";
    }

    return data;
}

function obj2JsonString() {
    input = JSON.parse(json_data);

    var output = [];
    for (var i = 0; i < input.sites.length; i++) {
        var obj = {};
        obj.ShowName = input.sites[i].name;
        obj.Url = input.sites[i].url;
        output.push(obj);
    }

    data = '{"obj":'+JSON.stringify(output)+'}';
    return data;
}


    02.CS

// See https://aka.ms/new-console-template for more information
using Jint;

//出處/原始教學 網站
//https://github.com/sebastienros/jint
//https://www.youtube.com/watch?v=yCs6UmogKEg&t=57s
//https://docs.microsoft.com/zh-tw/shows/code-conversations/sebastien-ros-on-jint-javascript-interpreter-net

//延伸教學 網站
//https://blog.no2don.com/2020/03/cnet-core-c-jint-javascript.html
namespace CS_test_Jint
{
    public class TestClass
    {

        public string GetStringFromClassFunction(string str)
        {
            return str + ", 您好我來自於 TestClass-GetStringFromClassFunction。";
        }
    }

    class Program
    {
        static void pause()
        {
            Console.WriteLine("\nPress any key to terminate...");
            Console.ReadKey();
        }

        //---
        //fun,js
        static int Sum(int x = 19, int y = 46)
        {
            var engine = new Engine();

            engine.Execute(System.IO.File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + "Script" +
                Path.DirectorySeparatorChar + "func.js"));

            var result = engine.Execute("GetSum(" + x + "," + y + ")").GetCompletionValue();

            return Convert.ToInt32(result.AsNumber());
        }

        static string Echo(string str = "DONMA")
        {
            //在 javascript 中,Echo  function 裡面並沒有 str 的參數,這樣我直接透過 C# 端定義一個 str 的變數,呼叫後並且取得回傳值。
            var engine = new Engine();

            engine.Execute(System.IO.File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + "Script" +
                Path.DirectorySeparatorChar + "func.js"));

            engine.SetValue("str", str);

            var result = engine.Execute("Echo()").GetCompletionValue();

            return result.AsString();
        }

        static string DoubleCall(string str = "當麻")
        {
            //先建立一個 TestClass ,並且讓 javascript 可以呼叫 TestClass 中 GetStringFromClassFunction 並且在回傳給 C# 端
            var engine = new Engine();

            engine.SetValue("testapi", new TestClass());

            engine.Execute(System.IO.File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + "Script" +
                Path.DirectorySeparatorChar + "func.js"));

            var result = engine.Execute("testapi.GetStringFromClassFunction('" + str + "')").GetCompletionValue();


            return result.AsString();
        }

        static String CallSum(int x = 19, int y = 46)
        {
            var engine = new Engine();

            engine.Execute(System.IO.File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + "Script" +
                Path.DirectorySeparatorChar + "func.js"));

            var result = engine.Execute("JSCallJS(" + x + "," + y + ")").GetCompletionValue();

            return result.AsString();
        }

        static String JS_ParseJson()
        {
            string text = "{ \"sites\" : [" +
                          "{ \"name\":\"Runoob\" , \"url\":\"www.runoob.com\" }," +
                          "{ \"name\":\"Google\" , \"url\":\"www.google.com\" }," +
                          "{ \"name\":\"Taobao\" , \"url\":\"www.taobao.com\" } ]}";

            var engine = new Engine();

            engine.Execute(System.IO.File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + "Script" +
                Path.DirectorySeparatorChar + "func.js"));

            engine.SetValue("json_data", text);

            var result = engine.Execute("parseJson()").GetCompletionValue();

            return result.AsString();
        }

        static String JS_CreateJsonString()
        {
            string text = "{ \"sites\" : [" +
                          "{ \"name\":\"Runoob\" , \"url\":\"www.runoob.com\" }," +
                          "{ \"name\":\"Google\" , \"url\":\"www.google.com\" }," +
                          "{ \"name\":\"Taobao\" , \"url\":\"www.taobao.com\" } ]}";

            var engine = new Engine();

            engine.Execute(System.IO.File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + "Script" +
                Path.DirectorySeparatorChar + "func.js"));

            engine.SetValue("json_data", text);

            var result = engine.Execute("obj2JsonString()").GetCompletionValue();

            return result.AsString();
        }
        //---fun,js

        static void Main(string[] args)
        {
            var engine = new Engine();

            /*
            //單行JS直譯測試,確定Jint Lib可用
            Console.WriteLine(engine.Execute("2+5*12").GetCompletionValue());
            */

            /*
            //透過C#無限迴圈,製作一個CMD的可輸入的JS直譯器
            // x=12
            // y=2
            // z=x+y
            //function add(x,y){return (x+y);}
            //add(10,20.5)
            //add(add (10,20),-20.5)
            while (true)
            {
                Console.Write("> ");
                var Command = Console.ReadLine();
                var Result = engine.Execute(Command).GetCompletionValue();
                Console.WriteLine(Result);
            }
            //*/

            //*
            //測試 https://blog.no2don.com/2020/03/cnet-core-c-jint-javascript.html 網站現成 JS檔 直譯呼叫使用
            Console.WriteLine(Sum());
            Console.WriteLine(Echo());
            Console.WriteLine(DoubleCall());
            Console.WriteLine(String.Format("19+46+10={0}", CallSum()));
            //*/

            //JSON基本測試
            Console.WriteLine(JS_ParseJson());
            Console.WriteLine(JS_CreateJsonString());

            pause();
        }
    }
}

2 thoughts on “C# 底下 的 javascript(JS) 直譯器 (interpreter) [CS_test_jint project]

  1. 恭喜老爺 賀喜夫人

    我上星期 要開發『阿薩布魯 直譯器(interpreter)』的計畫 已經正式終止

    正所謂: 實力不夠, GOOGLE(GITHUB)來湊

    我今早 GITHUB找到 jint 專案,相關資料網址如下
    https://github.com/sebastienros/jint

    所以我上星期可以算是上班純吹冷氣打混摸魚

    我今早 將我找到的新方向報告老闆,還得到稱讚 哈哈

    有需要外掛直譯器的人,建議可以到GITHUB搜尋 interpreter 看看是否有適合自己 合用的

發表迴響

你的電子郵件位址並不會被公開。 必要欄位標記為 *