Wednesday, February 19, 2014

Jint tutorial 002 - Exporting a C# object in 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).

In this tutorial I want to demonstrate how to create a C# class and expose one instance as a singleton in JavaScript world.
    
    public class Storage
    {
        private string GetFileName()
        {
            return string.Format(@"{0}\Storage.txt", Environment.GetEnvironmentVariable("TEMP"));
        }
        public void save(string text) 
        {
            System.IO.File.WriteAllText(this.GetFileName(), text);
        }
        public string read()
        {
            return System.IO.File.ReadAllText(this.GetFileName());
        }
    }
    
    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()
        {
            return new Engine()
                        .SetValue("storage", new Storage()) // Export the C# instance as storage
                        .SetValue("print", new Action<object>(Print));
        }

        static void Main(string[] args)
        {
            var source = @"

                storage.save('Hello World');
                var text = storage.read();
                print('storage value:'+text);             
            ";
            CreateEngine().Execute(source);
            Console.ReadLine();
        }
    }

No comments:

Post a Comment