IronRuby作为.NET中的脚本语言

rub*_*111 8 .net c# ruby ironruby scripting-interface

我想在我的.NET项目中使用IronRuby作为脚本语言(例如Lua).例如,我希望能够从Ruby脚本订阅特定事件,在宿主应用程序中触发,并从中调用Ruby方法.

我正在使用此代码来实例化IronRuby引擎:

Dim engine = Ruby.CreateEngine()
Dim source = engine.CreateScriptSourceFromFile("index.rb").Compile()
' Execute it
source.Execute()
Run Code Online (Sandbox Code Playgroud)

假设index.rb包含:

subscribe("ButtonClick", handler)
def handler
   puts "Hello there"
end
Run Code Online (Sandbox Code Playgroud)

我如何能:

  1. 使用C#方法订阅(在主机应用程序中定义)可以从index.rb中看到吗?
  2. 从宿主应用程序调用以后的处理程序方法?

Sha*_*man 7

您可以使用.NET事件并在IronRuby代码中订阅它们.例如,如果您的C#代码中有下一个事件:

public class Demo
{
    public event EventHandler SomeEvent;
}
Run Code Online (Sandbox Code Playgroud)

然后在IronRuby中,您可以按如下方式订阅它:

d = Demo.new
d.some_event do |sender, args|
    puts "Hello there"
end
Run Code Online (Sandbox Code Playgroud)

要在Ruby代码中使用.NET类,请使用a ScriptScope并将class(this)添加为变量并从Ruby代码中访问它:

ScriptScope scope = runtime.CreateScope();
scope.SetVariable("my_class",this);
source.Execute(scope);
Run Code Online (Sandbox Code Playgroud)

然后从Ruby:

self.my_class.some_event do |sender, args|
    puts "Hello there"
end
Run Code Online (Sandbox Code Playgroud)

要在Ruby代码中使用Demo类以便初始化它(Demo.new),您需要使IronRuby使程序集"可被发现".如果程序集不在GAC中,则将程序集目录添加到IronRuby的搜索路径:

var searchPaths = engine.GetSearchPaths();
searchPaths.Add(@"C:\My\Assembly\Path");
engine.SetSearchPaths(searchPaths);
Run Code Online (Sandbox Code Playgroud)

然后在您的IronRuby代码中,您可以要求组装,例如:require "DemoAssembly.dll"然后根据需要使用它.