5

我想在我的 C# 应用程序中使用 RubyGem。

我已经下载了 IronRuby,但我不确定如何启动和运行。他们的下载包括 ir.exe,其中包括一些 DLL,例如 IronRuby.dll。

在我的 .NET 项目中引用 IronRuby.dll 后,如何将 *.rb 文件的对象和方法公开给我的 C# 代码?

非常感谢,

迈克尔

4

1 回答 1

5

这是您进行互操作的方式:

确保你有对IronRuby, IronRuby.Libraries,Microsoft.ScriptingMicrosoft.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();


        }
    }
}

请注意,运行时有一个 ExecuteFile,您可以使用它来执行您的文件。

让宝石继续前进

  1. 确保使用安装 gemigem.exe
  2. 您可能必须使用 Engine.SetSearchPaths 设置一些搜索路径
于 2009-09-17T22:39:05.197 回答