tags:

views:

206

answers:

1

I'd like to use a RubyGem in my C# application.

I've downloaded IronRuby, but I'm not sure how to get up and running. Their download includes ir.exe, and it includes some DLLs such as IronRuby.dll.

Once IronRuby.dll is referenced in my .NET project, how do I expose the objects and methods of an *.rb file to my C# code?

Thanks very much,

Michael

+2  A: 

This is how you do interop:

Make sure you have refs to IronRuby, IronRuby.Libraries, Microsoft.Scripting and 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();


        }
    }
}

Note, Runtime has an ExecuteFile which you can use to execute your file.

To get the Gems going

  1. Make sure you install your gem using igem.exe
  2. you will probably have to set some search paths using Engine.SetSearchPaths
Sam Saffron
I think I would rather put bamboo shoots under my fingernails than do this.
Robert Harvey
Granted, its hairy, but doable. Sure with dynamic support this will get easier.
Sam Saffron
Thank you, Sam -- exactly what I was looking for.
kaneuniversal