How to convert C# types to IronRuby types and vice versa?

741 Views Asked by At

For example:

ruby code (just for test):

def process_initial_array (ar)
     ar.join(" ")
end

c# code: Here I create List of strings and pass it to the IronRuby

List<string> source_values = new List<string>();

it fills;

label2.Text=IronRuby.CSharp.BasicInteraction.calculator(source_values);


namespace IronRuby.CSharp
{
    public class BasicInteraction
    {internal static string calculator(List<string> source_values)
        {
            var rubyEngine = Ruby.CreateEngine();
            var scope = rubyEngine.ExecuteFile("math_logic.rb");
            string result = rubyEngine.Operations.InvokeMember(scope, "process_initial_array", source_values);
            return result;
        }
    }
}

It evokes:

An unhandled exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' occurred in Anonymously Hosted DynamicMethods Assembly

Additional information: Unable to convert implicitly "IronRuby.Builtins.MutableString" to "string". There is explicit conversion.

OK, I found IronRuby string method to_clr_string in related questions, so the question is where I can find documentation about same methods for other types?

1

There are 1 best solutions below

0
On

After a brief look on the IronRuby source code I could only find to_clr_string and to_clr_type (to convert to System.Type) that seem to be relevant to your question. Thus, I assume those are the only conversion methods you need to convert between built-in ruby types and CLR types. Other types should be the same types as their CLR counterparts.

Note that there're also other methods to convert from ruby strings to other primitive types like int (to_i) and double (to_f).

In your example, you could explicitly convert the result to string:

var result = (string)rubyEngine.Operations.InvokeMember(
  scope, "process_initial_array", source_values);

This way, you don't have to call to_clr_string on the Ruby side.