IronRuby 作为 .NET 中的脚本语言
我想使用 IronRuby 作为脚本语言(例如 Lua)在我的 .NET 项目中。 例如,我希望能够从 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# 方法 Subscribe (在主机应用程序中定义)从 index.rb 可见?
- 稍后从主机应用程序调用处理程序方法?
I want to use IronRuby as a scripting language (as Lua, for example) in my .NET project.
For example, I want to be able to subscribe from a Ruby script to specific events, fired in the host application, and call Ruby methods from it.
I'm using this code for instantiating the IronRuby engine:
Dim engine = Ruby.CreateEngine()
Dim source = engine.CreateScriptSourceFromFile("index.rb").Compile()
' Execute it
source.Execute()
Supposing index.rb contains:
subscribe("ButtonClick", handler)
def handler
puts "Hello there"
end
How do I:
- Make C# method Subscribe (defined in host application) visible from index.rb?
- Invoke later handler method from the host application?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以仅使用 .NET 事件并在 IronRuby 代码中订阅它们。例如,如果您的 C# 代码中有下一个事件:
那么在 IronRuby 中,您可以按如下方式订阅它:
要使 .NET 类在 Ruby 代码中可用,请使用
ScriptScope
并添加您的class (this
) 作为变量并从 Ruby 代码中访问它:然后从 Ruby 中访问它:
要在 Ruby 代码中使用 Demo 类以便可以初始化它 (Demo.new),您需要需要使该程序集可以被 IronRuby“发现”。如果程序集不在 GAC 中,则将程序集目录添加到 IronRuby 的搜索路径中:
然后在 IronRuby 代码中,您可以需要该程序集,例如:
require "DemoAssembly.dll"
然后使用它不管你想要什么。You can just use .NET events and subscribe to them within your IronRuby code. For example, if you have the next event in your C# code:
Then in IronRuby you can subscribe to it as follows:
To make your .NET class available within your Ruby code, use a
ScriptScope
and add your class (this
) as a variable and access it from within your Ruby code:And then from Ruby:
To have the Demo class available within the Ruby code so you can initialize it (Demo.new), you need to make the assembly "discoverable" by IronRuby. If the assembly is not in the GAC then add the assembly directory to IronRuby's search paths:
Then in your IronRuby code you can require the assembly, for example:
require "DemoAssembly.dll"
and then just use it however you want.