我该如何在.NET中使用Ruby代码?

5
我想在我的C#应用程序中使用RubyGem。
我已经下载了IronRuby,但我不确定该如何开始。他们的下载包括ir.exe以及一些DLL文件,例如IronRuby.dll。
一旦在我的.NET项目中引用了IronRuby.dll,如何将*.rb文件的对象和方法暴露给我的C#代码?
非常感谢,
迈克尔

很难找到关于这个的文档,难怪你感到困惑。 - Sam Saffron
1个回答

5

以下是Interop的实现方法:

确保您已经引用了IronRubyIronRuby.LibrariesMicrosoft.Scripting以及Microsoft.Scripting.Core

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IronRuby;
using IronRuby.Builtins;
using IronRuby.Runtime;

namespace ConsoleApplication7 {
    class Program {
        static void Main(string[] args) {
            var runtime = Ruby.CreateRuntime();
            var engine = runtime.GetRubyEngine();

            engine.Execute("def hello; puts 'hello world'; end");

            string s = engine.Execute("hello") as string;
            Console.WriteLine(s);
            // outputs "hello world"

            engine.Execute("class Foo; def bar; puts 'hello from bar'; end; end");
            object o = engine.Execute("Foo.new");
            var operations = engine.CreateOperations();
            string s2 = operations.InvokeMember(o, "bar") as string; 
            Console.WriteLine(s2);
            // outputs "hello from bar"

            Console.ReadKey();


        }
    }
}

注意,Runtime有一个ExecuteFile方法可以用于执行您的文件。

要启动Gems

  1. 确保使用igem.exe安装您的gem。
  2. 您可能需要使用Engine.SetSearchPaths设置一些搜索路径。

2
我想我宁愿在我的指甲下放竹笋也不愿意做这件事。 - Robert Harvey
虽然有些复杂,但是可以做到。当然,有了动态支持,这将变得更容易。 - Sam Saffron

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接