Skip to content
Prev Previous commit
Next Next commit
make BorrowedReference readonly ref struct
  • Loading branch information
lostmsu committed Feb 13, 2020
commit 2d11f829c3fcbfafd043ce3f1ca1518445f4ff9b
17 changes: 9 additions & 8 deletions src/runtime/BorrowedReference.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
namespace Python.Runtime
{
using System;
ref struct BorrowedReference
readonly ref struct BorrowedReference
{
public IntPtr Pointer;
public readonly IntPtr Pointer;
public bool IsNull => this.Pointer == IntPtr.Zero;

public PyObject ToPyObject()
Expand All @@ -13,13 +13,14 @@ public PyObject ToPyObject()
Runtime.XIncref(this.Pointer);
return new PyObject(this.Pointer);
}
}

static class BorrowedReferenceExtensions {
[Obsolete("Use overloads, that take BorrowedReference or NewReference")]
public static IntPtr DangerousGetAddress(this in BorrowedReference reference)
=> reference.IsNull() ? throw new NullReferenceException() : reference.Pointer;
public static bool IsNull(this in BorrowedReference reference)
=> reference.Pointer == IntPtr.Zero;
public IntPtr DangerousGetAddress()
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Use a property named Address can be more fit?
Why I have to be warned if I trying use the raw pointer, seems it doesn't make any sense. Or just don't expose the interface and use explicit operator IntPtr instead.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

This is modeled after SafeHandle class and its DangerousGetHandle method.
The whole point of introducing these references is to get rid of IntPtrs entirely. It should warn you against converting into IntPtr. Maybe Obsolete part is unnecessary as Dangerous sounds like a warning enough. I will remove Obsolete.

=> this.IsNull ? throw new NullReferenceException() : this.Pointer;

BorrowedReference(IntPtr pointer)
{
this.Pointer = pointer;
}
}
}