IronRuby作为.NET中的脚本语言

8
我希望在我的.NET项目中使用IronRuby作为脚本语言(例如Lua)。例如,我希望能够从Ruby脚本订阅在宿主应用程序中触发的特定事件,并从中调用Ruby方法。
我正在使用以下代码实例化IronRuby引擎:
Dim engine = Ruby.CreateEngine()
Dim source = engine.CreateScriptSourceFromFile("index.rb").Compile()
' Execute it
source.Execute()

假设 index.rb 包含:

subscribe("ButtonClick", handler)
def handler
   puts "Hello there"
end

我该如何实现以下功能:

  1. 如何使主机应用程序定义的C#方法Subscribe能够从index.rb中访问?
  2. 如何从主机应用程序中延迟调用handler方法?
1个回答

7

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

public class Demo
{
    public event EventHandler SomeEvent;
}

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

d = Demo.new
d.some_event do |sender, args|
    puts "Hello there"
end

为了使你的.NET类可以在Ruby代码中使用,需要使用ScriptScope,将你的类(this)作为变量添加并从Ruby代码中访问它:
ScriptScope scope = runtime.CreateScope();
scope.SetVariable("my_class",this);
source.Execute(scope);

然后从Ruby开始:

self.my_class.some_event do |sender, args|
    puts "Hello there"
end

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

var searchPaths = engine.GetSearchPaths();
searchPaths.Add(@"C:\My\Assembly\Path");
engine.SetSearchPaths(searchPaths);

然后在你的IronRuby代码中,你可以引用这个程序集,例如:require "DemoAssembly.dll",然后随意使用它。


1
非常感谢。 但是仍然有一个问题。如何使Demo类(而不是它的实例)在ruby代码中可用,以便我们能够实例化它?例如:d = Demo.new - rubyist111
将答案添加到原始答案正文的上方。 - Shay Friedman
使用最新的IronRuby(我相信是1.13),您将获得一个固定大小的searchPaths集合,如果尝试添加到其中会引发异常。您需要创建自己的集合,然后复制值。 - ashes999

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接