C# IronRuby作为.NET中的脚本语言

C# IronRuby作为.NET中的脚本语言,c#,.net,ruby,ironruby,scripting-interface,C#,.net,Ruby,Ironruby,Scripting Interface,我想在.NET项目中使用IronRuby作为脚本语言(例如)。 例如,我希望能够从Ruby脚本订阅主机应用程序中触发的特定事件,并从中调用Ruby方法 我使用以下代码实例化IronRuby引擎: Dim engine = Ruby.CreateEngine() Dim source = engine.CreateScriptSourceFromFile("index.rb").Compile() ' Execute it source.Execute() 假设index.rb包含: subsc

我想在.NET项目中使用IronRuby作为脚本语言(例如)。 例如,我希望能够从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
我如何:

  • 使C#methodSubscribe(在主机应用程序中定义)在index.rb中可见
  • 是否稍后从主机应用程序调用处理程序方法

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

    然后在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代码中,您可以要求程序集,例如:
    要求“DemoAssembly.dll”
    ,然后根据需要使用它。

    非常感谢。但还有一个问题。如何在ruby代码中提供演示类(而不是它的实例),以便我们能够实例化它?例如:d=Demo.new将答案添加到上面原始答案的正文中。使用最新的IronRuby(我相信是1.13),您将获得一个固定大小的集合,用于
    搜索路径
    ,如果您尝试添加该集合,则会引发异常。您需要创建自己的集合,并复制这些值。
    var searchPaths = engine.GetSearchPaths();
    searchPaths.Add(@"C:\My\Assembly\Path");
    engine.SetSearchPaths(searchPaths);