Search code examples
wpfironpythonembedding

Embedded IronPython scripts and converting types


I've got a WPF application that embeds IronPython to use as a scripting language. I've got an object model that IronPython scripts can use to do 'stuff'.

However I've come across a strange problem that I've solved in a way that I don't believe is correct.

In my script I want to type the following to set the location of an object in WPF.

map.CanvasLocation = 10,10

This comes up with an exception saying that it cannot convert from PythonTuple to System.Windows.Point.

I've currently solved that using a custom type converter in my c# object, but I'm not sure if this is the best way to do it.

Is there a way to tell IronPython or .Net in general how to convert from one type to another that can be extended at run time?


Solution

  • The way I do this is to use TypeDescriptor to add a type converter attribute to PythonTuple at runtime.

    TypeDescriptor.AddAttributes(typeof(PythonTuple), 
        new TypeConverterAttribute(typeof(Converter)));
    

    Then I use the following code to find the converter in the attribute setter (SetMemberAfter method)

    var converter = TypeDescriptor.GetConverter(value);
    if (converter.CanConvertTo(destinationType))
    {
        var destinationValue = converter.ConvertTo(value, destinationType);
        return destinationValue;
    }
    else
    {
        throw new InvalidOperationException("Cannot convert from {0} to {1}".UIFormat(
            value == null ? "null" : value.GetType().Name, destinationType.Name));
    }