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

Skip to content

Commit d46878c

Browse files
committed
make .NET classes, that have __call__ method callable from Python #890
1 parent 805f92b commit d46878c

File tree

2 files changed

+16
-2
lines changed

2 files changed

+16
-2
lines changed

src/runtime/Python.Runtime.15.csproj

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
<SolutionDir Condition="$(SolutionDir) == '' Or $(SolutionDir) == '*Undefined*'">..\..\</SolutionDir>
2020
<PythonBuildDir Condition="'$(PythonBuildDir)' == ''">$(SolutionDir)\bin\</PythonBuildDir>
2121
<PublishDir>$(PythonBuildDir)\$(TargetFramework)\</PublishDir>
22-
<LangVersion>6</LangVersion>
22+
<LangVersion>7.3</LangVersion>
2323
<AllowUnsafeBlocks>True</AllowUnsafeBlocks>
2424
<AssemblyOriginatorKeyFile>..\pythonnet.snk</AssemblyOriginatorKeyFile>
2525
<CustomDefineConstants Condition="'$(CustomDefineConstants)' == ''">$(PYTHONNET_DEFINE_CONSTANTS)</CustomDefineConstants>

src/runtime/classobject.cs

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
using System;
22
using System.Reflection;
3+
using System.Runtime.InteropServices;
34

45
namespace Python.Runtime
56
{
@@ -294,7 +295,20 @@ public static IntPtr tp_call(IntPtr ob, IntPtr args, IntPtr kw)
294295

295296
if (cb.type != typeof(Delegate))
296297
{
297-
Exceptions.SetError(Exceptions.TypeError, "object is not callable");
298+
IntPtr dict = Marshal.ReadIntPtr(tp, TypeOffset.tp_dict);
299+
IntPtr methodObjectHandle = Runtime.PyDict_GetItemString(dict, "__call__");
300+
if (methodObjectHandle == IntPtr.Zero || methodObjectHandle == Runtime.PyNone)
301+
{
302+
Exceptions.SetError(Exceptions.TypeError, "object is not callable");
303+
return IntPtr.Zero;
304+
}
305+
306+
if (GetManagedObject(methodObjectHandle) is MethodObject methodObject)
307+
{
308+
return methodObject.Invoke(ob, args, kw);
309+
}
310+
311+
Exceptions.SetError(Exceptions.TypeError, "instance has __call__, but it is not supported by Python.NET");
298312
return IntPtr.Zero;
299313
}
300314

0 commit comments

Comments
 (0)