can you typecast a .NET object in IronPython?
Asked Answered
B

4

9

I'm interfacing with a .NET API in IronPython. The API is returning an object of the wrong type (some kind of generic object). I suspect that the problem is not showing up in their C# code because the type declaration when the object is constructed is forcing the returned object to the correct type. Is it possible to typecast an .NET object in IronPython? I think this would do the trick.

Boundary answered 17/9, 2009 at 15:5 Comment(2)
Could you elaborate a bit more? What do you mean by wrong type?Coition
It appears that IronPython always populates an object's members according to its "real" type (since it uses reflection to determine that type). Can you give us an example where this doesn't stand?Herzberg
T
12

To force a conversion you can do:

import clr
convertedObject = clr.Convert(someObject, someType)

This will search for and run implicit/explicit conversions if one exists.

Note: available since IronPython 2.6.

Teresita answered 17/9, 2009 at 18:6 Comment(3)
I couldn't get this to work. I couldn't find a "Convert" method in my IronPython clr.Boundary
Convert invokes an explicit/implicit conversion method if there is one; if there isn't, it returns the object unchanged. It can't e.g. cast an object to its parent type.Herzberg
If I try to use this to cast an UInt32 to an Int16 I get an OverflowException. Is there a way to do this that works like an explicit var y = (short)x; cast?Undemonstrative
K
1

If you need to cast numeric value to an enum use the following, because the code above does not work for enums, but only for reference types:

Enum.ToObject(CustomEnumType, value)
Karame answered 16/10, 2014 at 11:38 Comment(0)
S
0

I had a similar problem on a project a few months ago. This was my fix:

import clr

clr.GetPythonType(x)

x can be a .NET type or a type that is in a dll file that you have imported using clr.

I am not a C# programmer, but I have been told by C# programmer colleagues that this code in C# would be:

typeof(x)

Hope this helps

Schumann answered 6/11, 2009 at 16:59 Comment(0)
M
0

clr.Convert doesnt exist in IronPython 2.0 . This is not a solution to typecast a .NET object in IronPython?, but it's a workaround to convert the data if you really need it to use it from IronPython

Create a class like this in VB.NET and compile it into a DLL

Imports Microsoft.VisualBasic

    Public Class MyConvert

        Shared Function converttype(ByVal value As String) As Integer
            Return CInt(value)
        End Function

    End Class

Then in IronPython you do

clr.AddReference('MyConvert')
from MyConvert import converttype         
converted_value = converttype("2.0")
Machmeter answered 11/1, 2011 at 14:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.