gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 06:54:13 24 4
gpt4 key购买 nike

我想在我的 .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# 方法订阅(在主机应用程序中定义)对 index.rb 可见?
  2. 稍后从主机应用程序调用处理程序方法?

最佳答案

您可以只使用 .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

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

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

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

关于c# - IronRuby 作为 .NET 中的脚本语言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2921320/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com