I have yet to find a simple clear example of using multiple files when embedding IronPython or IronRuby in Silverlight, so I decided to share an example I have been working on.
NOTE: During testing have found this does not work with 0.91 or 0.92 of the DLR. I guess there is a bug with imports and it should be fixed any day now. Go here and click all releases to get 0.90 of the IronRuby and IronPython dlls.
Here is the code in my MainPage.xaml.cs:
public delegate string pyFunc(string s);
public delegate IronRuby.Builtins.MutableString rbFunc(string s);
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
pythonblock.Text = DoPython();
rubyblock.Text = DoRuby();
}
private string DoPython()
{
var setup = Python.CreateRuntimeSetup(null);
setup.HostType = typeof(BrowserScriptHost);
var runtime = new ScriptRuntime(setup);
var engine = Python.GetEngine(runtime);
var scope = engine.CreateScope();
var mscope = engine.CreateScope();
var module = engine.CreateScriptSourceFromFile("module1.py");
module.Execute(mscope);
runtime.Globals.SetVariable("module1", mscope);
var source = engine.CreateScriptSourceFromFile("main.py");
source.Execute(scope);
var func = scope.GetVariable<pyFunc>("hello");
return func("world");
}
private string DoRuby()
{
var setup = new ScriptRuntimeSetup();
setup.HostType = typeof(BrowserScriptHost);
setup.AddRubySetup();
var runtime = new ScriptRuntime(setup);
var engine = Ruby.GetEngine(runtime);
var scope = engine.CreateScope();
var mscope = engine.CreateScope();
var module = engine.CreateScriptSourceFromFile("module1.rb");
module.Execute(mscope);
runtime.Globals.SetVariable("module1", mscope);
var source = engine.CreateScriptSourceFromFile("main.rb");
source.Execute(scope);
var func = scope.GetVariable<rbFunc>("hello");
return func("world");
}
}
Here are the source files:
main.py:
import module1
def hello(s):
return module1.f1('python hello ' + s)
module1.py:
def f1(s):
return 'python f1: ' + s
main.rb:
require "module1"
def hello(s)
f1('ruby hello ' + s)
end
module1.rb:
def f1(s)
'ruby f1: ' + s
end
I hope this is helpful and if anyone has any suggestions for improvement please let me know.