Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Merged
Show file tree
Hide file tree
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
Prev Previous commit
Next Next commit
Add int constructor for (U)IntPtr
  • Loading branch information
filmor committed Jul 11, 2022
commit 65a6408ac772b3c071aa34ce977f54224743ce92
18 changes: 17 additions & 1 deletion src/runtime/Types/ClassObject.cs
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ private static NewReference NewString(BorrowedReference args, BorrowedReference

/// <summary>
/// Create a new Python object for a primitive type
///
///
/// The primitive types are Boolean, Byte, SByte, Int16, UInt16,
/// Int32, UInt32, Int64, UInt64, IntPtr, UIntPtr, Char, Double,
/// and Single.
Expand Down Expand Up @@ -170,6 +170,14 @@ private static NewReference NewPrimitive(BorrowedReference tp, BorrowedReference
break;
}
}
else if (Runtime.PyInt_Check(op))
{
long? num = Runtime.PyLong_AsLongLong(op);
if (num is long n)
{
result = new IntPtr(n);
}
}
}

if (type == typeof(UIntPtr))
Expand All @@ -189,6 +197,14 @@ private static NewReference NewPrimitive(BorrowedReference tp, BorrowedReference
break;
}
}
else if (Runtime.PyInt_Check(op))
{
ulong? num = Runtime.PyLong_AsUnsignedLongLong(op);
if (num is ulong n)
{
result = new UIntPtr(n);
}
}
}

if (result == null && !Converter.ToManaged(op, type, out result, true))
Copy link
Member

@lostmsu lostmsu Jul 11, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we need a test for IntPtr constructor call with this path (e.g. parameter is neither CLR object nor Python int)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What do you expect to happen? It fails to convert, this is essentially the "old" code path. I'll add the test, though.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@filmor actually, nothing specific. Just want to ensure it does not error in a weird way and the error is actually helpful.

Expand Down
3 changes: 3 additions & 0 deletions tests/test_conversion.py
Original file line number Diff line number Diff line change
Expand Up @@ -689,10 +689,13 @@ def test_intptr_construction():
assert ob.UIntPtrField == UIntPtr.Zero

ob.IntPtrField = IntPtr(Int64(-1))
assert ob.IntPtrField == IntPtr(-1)
assert ob.IntPtrField.ToInt64() == -1

ob.IntPtrField = IntPtr(Int64(1024))
assert ob.IntPtrField == IntPtr(1024)
assert ob.IntPtrField.ToInt64() == 1024

ob.UIntPtrField = UIntPtr(UInt64(1024))
assert ob.UIntPtrField == UIntPtr(1024)
assert ob.UIntPtrField.ToUInt64() == 1024