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