您的位置:首页 > 编程语言 > Ruby

在C#中调用Ruby代码

2009-08-24 09:33 435 查看
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:

view plaincopy to clipboardprint?

using Microsoft.Scripting.Hosting;



var runtime = ScriptRuntime.Create();

runtime.ExecuteFile("MyController.rb")

using Microsoft.Scripting.Hosting;

var runtime = ScriptRuntime.Create();      
runtime.ExecuteFile("MyController.rb")

Where MyController.rb contains:

view plaincopy to clipboardprint?

class MyController

def do_foo a, b

puts a, b

end

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:

view plaincopy to clipboardprint?

var engine = runtime.GetEngine("Ruby");

// TODO: should check that the values are identifiers

var code = String.Format("{0}.new.method :{1}", "MyController", "do_foo");

var action = engine.CreateScriptSourceFromString(code).Execute();

var engine = runtime.GetEngine("Ruby");
// TODO: should check that the values are identifiers
var code = String.Format("{0}.new.method :{1}", "MyController", "do_foo");
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:

view plaincopy to clipboardprint?

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

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

The definitive reference is the DLR hosting specification.

Retrieved from "http://www.ironruby.net/Documentation/.NET/Hosting"
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: