2010-05-27 52 views
8

我想在我的.NET項目中使用IronRuby作爲腳本語言(例如Lua)。 例如,我希望能夠從Ruby腳本訂閱特定事件,在主機應用程序中觸發,並從中調用Ruby方法。IronRuby作爲.NET中的腳本語言

我使用這個代碼實例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#方法訂閱(在主機應用程序中定義)從index.rb可見?
  2. 以後調用處理程序方法從主機應用程序?

回答

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 

爲了讓你的Ruby代碼中提供您的.NET類,使用ScriptScope並添加類(this)作爲變量,並從Ruby代碼中訪問它:

ScriptScope scope = runtime.CreateScope(); 
scope.SetVariable("my_class",this); 
source.Execute(scope); 

然後從紅寶石:

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

要在Ruby代碼中提供Demo類,以便初始化它(Demo.new),需要使程序集可由IronRuby「發現」。如果程序集是不是在GAC然後添加組件目錄的IronRuby的搜索路徑:

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

然後在你的IronRuby代碼,你可以要求裝配,例如:require "DemoAssembly.dll",然後只用你想要的東西。

+1

非常感謝。 但仍有1個問題。如何在Ruby代碼中使用可用的Demo類(不是它的實例),以便我們能夠實例化它?例如:d = Demo.new – rubyist111 2010-05-27 18:16:13

+0

將答案添加到上面原始答案的正文中。 – 2010-05-27 19:06:25

+0

使用最新的IronRuby(1.13,我相信),您會爲'searchPaths'返回一個固定大小的集合,如果您嘗試添加它,則會引發異常。您需要創建自己的集合,然後複製這些值。 – ashes999 2013-09-19 15:26:33