Can Ruby import a .NET dll?

While IronRuby will make short work of talking to your .NET dll (it’ll be literally no code at all), it was abandoned by microsoft, and it never got a large enough open source community to keep it going after that event. I wouldn’t recommend it these days

Regarding the COM solution, this may actually be a good way to go.

You don’t need the RubyCOM library – that lets other COM objects call into ruby code. To load COM objects from ruby, you just need the win32ole library, which comes as part of the standard library on windows ruby.

Whether or not you can load the dll from COM will depend if the .NET dll was built to be ‘Com Visible’.
The .NET framework defines a ComVisibleAttribute, which can be applied to either an entire assembly, or specific classes within an assembly. If it is set to true for either the whole assembly, or any classes, then the dll will already be callable from COM without any wrapper code.

Here’s a test I did.

Create a new .NET dll project (class library). Here’s an example class I used:

using System;
using System.IO;

namespace ComLib
{
    public class LogWriter
    {
        public void WriteLine( string line )
        {
            using( var log = new StreamWriter( File.OpenWrite( @"c:\log.file" ) ) )
            {
                log.WriteLine( line );
            }
        }
    }
}

Now, under the visual studio project, there is a directory called Properties which contains AssemblyInfo.cs. In this file, there will be the following

[assembly: ComVisible( false )]

Change the false to true. If you don’t want every class in the assembly exposed to COM, then you can leave it set to false in AssemblyInfo.cs and instead put it above each class you want to expose, like this:

[ComVisible( true )]
public class LogWriter ....

Now right click on the dll project itself, and from the popup menu, select ‘properties’. In the list of sections, choose Build

Scroll down, and tick the ‘Register for COM interop’ checkbox. Now when you compile this DLL, visual studio will do the neccessary stuff to load the COM information into the registry. Note if you’re on vista you need to run VS as an administrator for this to work.

Now that this is done, recompile your dll, and then create a new ruby file.

In this ruby file, do this:

require 'win32ole'

lib = WIN32OLE.new('[Solution name].ComLib.LogWriter')
lib.WriteLine('calling .net from ruby via COM, hooray!')

Where [Solution name] is to be replaced by the name of the solution you just created (default: “ClassLibrary1”)

Ruby that ruby file, and presto! you should see that the text gets written to c:\log.file.

One problem with this solution is that it requires that the .NET dll is already Com Visible, or if it’s not, you have the ability to recompile it. If neither of these things are true, then you may have to look at other options.

Good luck!

Leave a Comment