Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonnet: Why are .NET enums type casted to int?

Why are .NET enums type casted to int?

E.g.: I want to generate an array of Objects where the first element is an Int32, the second element is an Double and the third element is an enumeration of the type DateTimeKind. See the following code:

import clr
from System import Array, DateTimeKind, Double, Enum, Int32, Object
a = Array[Object]([None, None, None])
a[0] = Int32(127)
a[1] = Double(12.4)
a[2] = DateTimeKind.Utc

But now the third element is of type int and not DateTimeKind.

I need the array a as argument when invoking a method (reflection, see https://stackoverflow.com/a/49997219/7556646).

I'm as well aware that I can generate a b = List[DataTimeKind]() and add elements to that list, see https://stackoverflow.com/a/44088399/7556646. The list b has the right type but when I access an element of the list b[0] then it's again an int.

So what can I do to cast an int to an enum?

like image 861
Wollmich Avatar asked Mar 16 '26 22:03

Wollmich


1 Answers

This not possible with pythonnet at the moment because pythonnet converts .NET enums to int, see https://github.com/pythonnet/pythonnet/issues/1220.

.NET enums should not be automatically converted to Python int and back

The only workaround would be to add a C# helper dll and call this helper dll from pythonnet.

like image 62
Wollmich Avatar answered Mar 18 '26 13:03

Wollmich



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!