[IronPython] Writing cross-language libraries that appear native

Doug Blank doug.blank at gmail.com
Mon Apr 4 17:24:38 CEST 2011


I'm working on writing C# libraries which can be imported by a variety
of .NET languages, DLR and otherwise, which appear native to the
language importing them.

For example, writing a C# function that can be used naturally in
IronPython as if it were written in Python, IronRuby as if it were
written in Ruby, and F# as if it were written in F#, etc.

I've encountered some gotchas that I thought I'd share, and looking
for any other points of advice in writing cross-language libraries.

1. IronRuby strings aren't really strings, so you need to pass them in
as an object, and call .ToString().

    public static string expects_string(object val) {
        return val.ToString();
    }

2. F# 2.0 doesn't seem to automatically convert a type to the
associated nullable type, so avoid nullable types as parameters.

    // AVOID:
    public static double? expects_nullable(double? var1=null) {
        return var1;
    }

    // BETTER:
    public static double? expects_nullable() {
        return null;
    }
    public static double expects_nullable(double var1) {
        return var1;
    }

3. IronPython and IronRuby lists and dictionaries implement IList and
IDictionary, so no problem with those.

    public static IDictionary<object,object> make_dict(object val) {
        if (val as IDictionary<object,object> != null) {
            return ((IDictionary<object,object>)val);
        } else
            throw new System.ArgumentException("object is not a dictionary");
    }

    public static IList<object> make_list(object val) {
        if (val as IList<object> != null) {
            return ((IList<object>)val);
        } else
            throw new System.ArgumentException("object is not a list");
    }

Any other suggestions?

-Doug



More information about the Ironpython-users mailing list