IronRuby as a scripting language in .NET
I want to use IronRuby as a scripting language (as Lua, for example) in my .NET project. For example, I want to be able to subscribe from a Ruby script to specific events, fired in the host application, and call Ruby methods from it.
I'm using this code for instantiating the IronRuby engine:
Dim engine = Ruby.CreateEngine()
Dim source = engine.CreateScriptSourceFromFile("index.rb").Compile()
' Execute it
source.Execute()
Supposing index.rb contains:
subscribe("ButtonClick", handler)
def handler
p开发者_如何学Cuts "Hello there"
end
How do I:
- Make C# method Subscribe (defined in host application) visible from index.rb?
- Invoke later handler method from the host application?
You can just use .NET events and subscribe to them within your IronRuby code. For example, if you have the next event in your C# code:
public class Demo
{
public event EventHandler SomeEvent;
}
Then in IronRuby you can subscribe to it as follows:
d = Demo.new
d.some_event do |sender, args|
puts "Hello there"
end
To make your .NET class available within your Ruby code, use a ScriptScope
and add your class (this
) as a variable and access it from within your Ruby code:
ScriptScope scope = runtime.CreateScope();
scope.SetVariable("my_class",this);
source.Execute(scope);
And then from Ruby:
self.my_class.some_event do |sender, args|
puts "Hello there"
end
To have the Demo class available within the Ruby code so you can initialize it (Demo.new), you need to make the assembly "discoverable" by IronRuby. If the assembly is not in the GAC then add the assembly directory to IronRuby's search paths:
var searchPaths = engine.GetSearchPaths();
searchPaths.Add(@"C:\My\Assembly\Path");
engine.SetSearchPaths(searchPaths);
Then in your IronRuby code you can require the assembly, for example: require "DemoAssembly.dll"
and then just use it however you want.
精彩评论