Wednesday, February 19, 2014

Jint tutorial 003 - Exporting a C# method that returns a JavaScript array to the JavaScript world

Reminder : Jint is a Javascript v 5 interpreter for the .NET Framework/Mono/Xamarin allowing to execute scripts in C# applications on Windows, MacOS, iOS, Android and Linux (Anywhere there is a C# 4.x compiler).

This tutorial demonstrates how to write and export a C# method that returns a JavaScript array to the JavaScript world.
       
    public class NumberGenerator
    {
        Jint.Engine _engine;

        public NumberGenerator(Jint.Engine engine)
        {
            this._engine = engine;
        }
        
        /// 
        /// Return an array of number to the JavaScript world
        /// 
        /// ArrayInstance
        public Jint.Native.Array.ArrayInstance getNumbers()
        {
            var l = new List<object>() {1, 2, 3};
            return ToJavaScriptArray(l, this._engine);
        }

        private static Jint.Native.Array.ArrayInstance ToJavaScriptArray(List<object> values, Jint.Engine engine)
        {
            var jsValues = new List<JsValue>();
            foreach(var v in values)
                jsValues.Add(JsValue.FromObject(engine, v));
            return (ArrayInstance)engine.Array.Construct(jsValues.ToArray());
        }
    }
    
    class Program
    {
        static Jint.Engine _engine;

        public static void Print(object s)
        {
            if (s == null)
                s = "null";
            Console.WriteLine(s.ToString());
        }

        private static Jint.Engine CreateEngine()
        {
            var engine = new Engine();
            return engine.SetValue("numberGenerator", new NumberGenerator(engine))
                         .SetValue("print", new Action<object>(Print));
        }

        static void Main(string[] args)
        {
            var source = @"
                var numbers = numberGenerator.getNumbers();
                print('numbers:' + JSON.stringify(numbers));
";
            CreateEngine().Execute(source);
            Console.ReadLine();
        }
    }


No comments:

Post a Comment