在C#中调用Ruby代码

Here is some code that we put together for the ASP.NET MVC team. They used it to prototype their IronRuby integration that we showed at Tech Ed 2008. Here's how you can execute a simple file:

  1. using Microsoft.Scripting.Hosting;   
  2.   
  3. var runtime = ScriptRuntime.Create();         
  4. runtime.ExecuteFile("MyController.rb")  

Where MyController.rb contains:

  1. class MyController   
  2.   def do_foo a, b   
  3.     puts a, b   
  4.   end  
  5. end  
class MyController
  def do_foo a, b
    puts a, b
  end
end

This will define the MyController class and the do_foo method. Here's some code that instantiates the controller and retrieves the action method:

  1. var engine = runtime.GetEngine("Ruby");   
  2. // TODO: should check that the values are identifiers   
  3. var code = String.Format("{0}.new.method :{1}""MyController""do_foo");   
  4. var action = engine.CreateScriptSourceFromString(code).Execute();  

The action variable now holds on do_foo method bound to the controller instance. You can invoke it by:

  1. var result = engine.Operations.Call(action, 1, 2);  

The definitive reference is the DLR hosting specification.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值