Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Proposal: Safe pointers#1043

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
filmor merged 9 commits intopythonnet:masterfromlosttech:features/SafePointers
Feb 26, 2020
Merged
Show file tree
Hide file tree
Changes from5 commits
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
26 changes: 26 additions & 0 deletionssrc/runtime/BorrowedReference.cs
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
namespace Python.Runtime
{
using System;
readonly ref struct BorrowedReference
{
public readonly IntPtr Pointer;
public bool IsNull => this.Pointer == IntPtr.Zero;

public PyObject ToPyObject()
{
if (this.IsNull) throw new NullReferenceException();

Runtime.XIncref(this.Pointer);
return new PyObject(this.Pointer);
}

[Obsolete("Use overloads, that take BorrowedReference or NewReference")]
public IntPtr DangerousGetAddress()
Copy link
Member

Choose a reason for hiding this comment

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

Use a property namedAddress 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 useexplicit operator IntPtr instead.

Copy link
MemberAuthor

Choose a reason for hiding this comment

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

This is modeled afterSafeHandle class and itsDangerousGetHandle method.
The whole point of introducing these references is to get rid ofIntPtrs entirely. It should warn you against converting intoIntPtr. MaybeObsolete part is unnecessary asDangerous sounds like a warning enough. I will removeObsolete.

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

BorrowedReference(IntPtr pointer)
{
this.Pointer = pointer;
}
}
}
26 changes: 26 additions & 0 deletionssrc/runtime/NewReference.cs
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
namespace Python.Runtime
{
using System;
[NonCopyable]
ref struct NewReference
Copy link
Member

Choose a reason for hiding this comment

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

Is it necessary to limit it as a stack-allocated value? If make it to a normal struct and rename it toPyReference, it can be assigned to a collection and implement the IDisposable forusing () usage.
For better usage, aBorrowedReference may be able to promote to aPyReference for using the implict operate overloading.

Copy link
MemberAuthor

Choose a reason for hiding this comment

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

With[NoCopyable] you won't be able to put it into a collection anyway. And without[NoCopyable] it does not provide any safety guarantees.

Having it asref struct saves you from addingref everywhere you take it.

Copy link
Member

Choose a reason for hiding this comment

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

But....sometimes I just want to put them into collections...😂

Copy link
MemberAuthor

Choose a reason for hiding this comment

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

Then you can still doDangerousGetHandle or create aPyObject from them.

Copy link
Member

Choose a reason for hiding this comment

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

But this type also has a purpose for reminding others that it's a reference don't forget to decref it, isn't it?

Copy link
MemberAuthor

Choose a reason for hiding this comment

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

Because it must be clear from code, that care is necessary around this scenario.

Copy link
MemberAuthor

Choose a reason for hiding this comment

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

Also, as mentioned above,[NoCopyable] would already prevent you from putting an instance into a collection, even ifref were removed. And[NoCopyable] is basically the sole purpose of this change, as if you do

NewReferencerefA=GetNewReferenceSomehow();NewReferencerefB=refA;

Then you already miappropriated refcounts.

Copy link
Member

Choose a reason for hiding this comment

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

Maybe more introduce a type namedPyHandle for that?

Copy link
Member

Choose a reason for hiding this comment

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

emmm, but that makeBorrowedReference embarrassed.

Copy link
MemberAuthor

Choose a reason for hiding this comment

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

@amos402 The idea withPyHandle can be reviewed separately. This PR is only for tracking new vs borrowed references as used in Python documentation for C API.

{
public IntPtr Pointer { get; set; }
public bool IsNull => this.Pointer == IntPtr.Zero;

public PyObject ToPyObject()
Copy link
Member

Choose a reason for hiding this comment

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

I prefer two methods:
ToPyObject: inref and create aPyObject, not assign thePointer to nullptr
AsPyObject: use this implementation

Copy link
MemberAuthor

Choose a reason for hiding this comment

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

Constructing a newPyObject from references should be done usingPyObject constructors (which can be added later). I agree though, thatToPyObject is not descriptive enough. MaybeMoveToPyObject orIntoPyObject?

{
if (this.IsNull) throw new NullReferenceException();

var result = new PyObject(this.Pointer);
this.Pointer = IntPtr.Zero;
return result;
}

public void Dispose()
{
if (!this.IsNull)
Runtime.XDecref(this.Pointer);
this.Pointer = IntPtr.Zero;
}
}
}
6 changes: 6 additions & 0 deletionssrc/runtime/NonCopyableAttribute.cs
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
namespace Python.Runtime
{
using System;
[AttributeUsage(AttributeTargets.Struct)]
class NonCopyableAttribute : Attribute { }
}
9 changes: 8 additions & 1 deletionsrc/runtime/Python.Runtime.15.csproj
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -30,7 +30,7 @@
<SolutionDir Condition="$(SolutionDir) == '' Or $(SolutionDir) == '*Undefined*'">..\..\</SolutionDir>
<PythonBuildDir Condition="'$(PythonBuildDir)' == ''">$(SolutionDir)\bin\</PythonBuildDir>
<PublishDir Condition="'$(TargetFramework)'!='net40'">$(PythonBuildDir)\$(TargetFramework)\</PublishDir>
<LangVersion>7.3</LangVersion>
<LangVersion>8.0</LangVersion>
<AllowUnsafeBlocks>True</AllowUnsafeBlocks>
<AssemblyOriginatorKeyFile>..\pythonnet.snk</AssemblyOriginatorKeyFile>
<CustomDefineConstants Condition="'$(CustomDefineConstants)' == ''">$(PYTHONNET_DEFINE_CONSTANTS)</CustomDefineConstants>
Expand DownExpand Up@@ -129,6 +129,13 @@
<PackageReference Include="Microsoft.TargetingPack.NETFramework.v4.5" Version="1.0.1" ExcludeAssets="All" PrivateAssets="All" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="NonCopyableAnalyzer" Version="0.5.1">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>

<Import Project="Sdk.targets" Sdk="Microsoft.NET.Sdk" />

<PropertyGroup>
Expand Down
5 changes: 4 additions & 1 deletionsrc/runtime/Python.Runtime.csproj
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -15,7 +15,7 @@
<SolutionDir Condition="$(SolutionDir) == '' Or $(SolutionDir) == '*Undefined*'">..\..\</SolutionDir>
<PythonBuildDir Condition=" '$(PythonBuildDir)' == '' ">$(SolutionDir)\bin\</PythonBuildDir>
<AppDesignerFolder>Properties</AppDesignerFolder>
<LangVersion>7.3</LangVersion>
<LangVersion>8.0</LangVersion>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<SignAssembly>false</SignAssembly>
<AssemblyOriginatorKeyFile>..\pythonnet.snk</AssemblyOriginatorKeyFile>
Expand DownExpand Up@@ -83,6 +83,7 @@
</Compile>
<Compile Include="arrayobject.cs" />
<Compile Include="assemblymanager.cs" />
<Compile Include="BorrowedReference.cs" />
Copy link
Member

Choose a reason for hiding this comment

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

Is it good for separate these three items to different files? They're small, related, and it make the project files be scattered.

Copy link
MemberAuthor

Choose a reason for hiding this comment

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

The might get more code later on. Generally, I prefer a type per file approach for anything except delegate types.

Copy link
Member

Choose a reason for hiding this comment

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

Or create a folder for them? Just just too far if they sorted by name I thought🤣

<Compile Include="classderived.cs" />
<Compile Include="classbase.cs" />
<Compile Include="classmanager.cs" />
Expand DownExpand Up@@ -119,6 +120,8 @@
<Compile Include="moduleobject.cs" />
<Compile Include="modulepropertyobject.cs" />
<Compile Include="nativecall.cs" />
<Compile Include="NewReference.cs" />
<Compile Include="NonCopyableAttribute.cs" />
<Compile Include="overload.cs" />
<Compile Include="propertyobject.cs" />
<Compile Include="pyansistring.cs" />
Expand Down
4 changes: 2 additions & 2 deletionssrc/runtime/assemblymanager.cs
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -145,7 +145,7 @@ internal static void UpdatePath()
probed.Clear();
for (var i = 0; i < count; i++)
{
IntPtr item = Runtime.PyList_GetItem(list, i);
BorrowedReference item = Runtime.PyList_GetItem(list, i);
string path = Runtime.GetManagedString(item);
if (path != null)
{
Expand DownExpand Up@@ -492,4 +492,4 @@ internal static Type[] GetTypes(Assembly a)
}
}
}
}
}
2 changes: 1 addition & 1 deletionsrc/runtime/methodbinder.cs
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -292,7 +292,7 @@ internal Binding Bind(IntPtr inst, IntPtr args, IntPtr kw, MethodBase info, Meth
for (int i = 0; i < pynkwargs; ++i)
{
var keyStr = Runtime.GetManagedString(Runtime.PyList_GetItem(keylist, i));
kwargDict[keyStr] = Runtime.PyList_GetItem(valueList, i);
kwargDict[keyStr] = Runtime.PyList_GetItem(valueList, i).DangerousGetAddress();
Copy link
MemberAuthor

Choose a reason for hiding this comment

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

This generates a compiler warning, that uncovers a potentially dangerous pattern, wherekwargsDict may contain borrowed references.

}
Runtime.XDecref(keylist);
Runtime.XDecref(valueList);
Expand Down
7 changes: 4 additions & 3 deletionssrc/runtime/pydict.cs
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -139,12 +139,13 @@ public PyObject Values()
/// </remarks>
public PyObject Items()
{
IntPtritems = Runtime.PyDict_Items(obj);
if (items == IntPtr.Zero)
using varitems = Runtime.PyDict_Items(this.obj);
Copy link
MemberAuthor

Choose a reason for hiding this comment

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

Afterdotnet/roslyn-analyzers#3305 is fixed we can configure build to fail here ifusing would be omitted

if (items.IsNull)
{
throw new PythonException();
}
return new PyObject(items);

return items.ToPyObject();
}


Expand Down
8 changes: 5 additions & 3 deletionssrc/runtime/runtime.cs
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -1509,6 +1509,8 @@ internal static IntPtr PyUnicode_FromString(string s)
return PyUnicode_FromUnicode(s, s.Length);
}

internal static string GetManagedString(in BorrowedReference borrowedReference)
=> GetManagedString(borrowedReference.DangerousGetAddress());
/// <summary>
/// Function to access the internal PyUnicode/PyString object and
/// convert it to a managed string with the correct encoding.
Expand DownExpand Up@@ -1591,7 +1593,7 @@ internal static bool PyDict_Check(IntPtr ob)
internal static extern IntPtr PyDict_Values(IntPtr pointer);

[DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)]
internal static externIntPtr PyDict_Items(IntPtr pointer);
internal static externNewReference PyDict_Items(IntPtr pointer);

[DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)]
internal static extern IntPtr PyDict_Copy(IntPtr pointer);
Expand DownExpand Up@@ -1631,13 +1633,13 @@ internal static IntPtr PyList_New(long size)
[DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)]
internal static extern IntPtr PyList_AsTuple(IntPtr pointer);

internal staticIntPtr PyList_GetItem(IntPtr pointer, long index)
internal staticBorrowedReference PyList_GetItem(IntPtr pointer, long index)
{
return PyList_GetItem(pointer, new IntPtr(index));
}

[DllImport(_PythonDll, CallingConvention = CallingConvention.Cdecl)]
private static externIntPtr PyList_GetItem(IntPtr pointer, IntPtr index);
private static externBorrowedReference PyList_GetItem(IntPtr pointer, IntPtr index);

internal static int PyList_SetItem(IntPtr pointer, long index, IntPtr value)
{
Expand Down

[8]ページ先頭

©2009-2025 Movatter.jp