views:

90

answers:

1

Working on a project that uses some IronPython scripts to as plug-ins, that utilize functionality coded in C#. In one of my C# classes, I have a property that is of type:

Dictionary<int, float>

I set the value of that property from the IronPython code, like this:

mc = MyClass()
mc.ValueDictionary = Dictionary[int, float]({1:0.0, 2:0.012, 3:0.024})

However, when this bit of code is run, it throws the following exception:

Microsoft.Scripting.ArgumentTypeException was unhandled by user code
  Message=expected Dictionary[int, Single], got Dictionary[int, float]

To make things weirder, originally the C# code used

Dictionary<int, double>

but I could not find a "double" type in IronPython, tried "float" on a whim and it worked fine, giving no errors. But now that it's using float on both ends (which it should have been using from the start) it errors, and thinks that the C# code is using the "Single" data type?!

I've even checked in the object browser for the C# library and, sure enough, it shows as using a "float" type and not "Single"

+4  A: 

I dont really see a question here, you very much answered everything yourself. I guess you are just asking because you are confused. So lets clear things up:

C# has the two floating point types: float (a keyword that is short for System.Single MSDN, 32 bit long) and double (keyword for System.Double MSDN, 64 bit long).

Python on the other side uses the float keyword/type to store a double precision floating point number, as the python documentation states:

Floating point numbers are implemented using double in C. All bets on their precision are off unless you happen to know the machine you are working with.

For that, on a x86 architecture, it is 64 bit long. This is the reason IronPython treats a python float as a .NET System.Double.

That said, those two methods will both work:

C#:

Dictionary<int, float> single_precision_dict;
Dictionary<int, double> double_precision_dict;

IronPython:

single_precision_dict = Dictionary[int, Single]({1:0.0, 2:0.012, 3:0.024})
double_precision_dict = Dictionary[int, float]({1:0.0, 2:0.012, 3:0.024})
Philip Daubmeier
Thank you, perfect answer. And yeah, I guess I did kind of already lay out what the mappings were, I just didn't know why. It just seemed counter intuative that float in C# wouldn't be float in Python.
Adam Haile
Youre welcome! I had a similar issue lately (C# / Python Interop). Its indeed very counter intuitive, as all C-like languages, Java and many more use `float` for single precision numbers.
Philip Daubmeier