【问题标题】:IronRuby as a scripting language in .NETIronRuby 作为 .NET 中的脚本语言
【发布时间】:2010-05-27 13:05:09
【问题描述】:

我想在我的 .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 方法?

【问题讨论】:

    标签: c# .net ruby ironruby scripting-interface


    【解决方案1】:

    您可以只使用 .NET 事件并在 IronRuby 代码中订阅它们。例如,如果您的 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
    

    要在 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个问题。如何在 ruby​​ 代码中以我们能够实例化它的方式使可用的 Demo 类(而不是它的实例)?例如:d = Demo.new
    • 将答案添加到上述原始答案的正文中。
    • 使用最新的 IronRuby(我相信是 1.13),你会得到一个固定大小的集合返回 searchPaths,如果你尝试添加它会抛出一个异常。您需要创建自己的集合并复制这些值。
    猜你喜欢
    • 2011-01-09
    • 2014-03-13
    • 1970-01-01
    • 2023-03-29
    • 2012-11-24
    • 2016-04-15
    • 1970-01-01
    • 2010-09-19
    • 1970-01-01
    相关资源
    最近更新 更多