Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Implements System.Decimal support
Convertes System.Decimal to decimal.decimal and vice-versa
  • Loading branch information
AlexCatarino committed Sep 28, 2017
commit 635316db1e1356fb31c6e87c1d4876be36f7a2ed
27 changes: 27 additions & 0 deletions src/runtime/converter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ private Converter()
private static Type flagsType;
private static Type boolType;
private static Type typeType;
private static IntPtr decimalCtor;

static Converter()
{
Expand All @@ -45,6 +46,9 @@ static Converter()
flagsType = typeof(FlagsAttribute);
boolType = typeof(Boolean);
typeType = typeof(Type);

IntPtr decimalMod = Runtime.PyImport_ImportModule("decimal");
if (decimalMod == null) throw new PythonException();
}


Expand Down Expand Up @@ -100,6 +104,9 @@ internal static IntPtr GetPythonTypeByAlias(Type op)
if (op == boolType)
return Runtime.PyBoolType;

if (op == decimalType)
return Runtime.PyFloatType;

return IntPtr.Zero;
}

Expand Down Expand Up @@ -221,6 +228,14 @@ internal static IntPtr ToPython(object value, Type type)
case TypeCode.UInt64:
return Runtime.PyLong_FromUnsignedLongLong((ulong)value);

case TypeCode.Decimal:
string d2s = ((decimal)value).ToString(nfi);
IntPtr d2p = Runtime.PyString_FromString(d2s);
IntPtr decimalArgs = Runtime.PyTuple_New(1);
Runtime.PyTuple_SetItem(decimalArgs, 0, d2p);

return Runtime.PyObject_CallObject(decimalCtor, decimalArgs);

default:
if (value is IEnumerable)
{
Expand Down Expand Up @@ -793,6 +808,18 @@ private static bool ToPrimitive(IntPtr value, Type obType, out object result, bo
Runtime.XDecref(op);
result = d;
return true;

case TypeCode.Decimal:
op = Runtime.PyObject_Str(value);
decimal m;
string sm = Runtime.GetManagedString(op);
if (!Decimal.TryParse(sm, NumberStyles.Number, nfi, out m))
{
goto type_error;
}
Runtime.XDecref(op);
result = m;
return true;
}


Expand Down