Skip to content

clrmethod working for python 2 #494

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 our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Jun 16, 2017
1 change: 1 addition & 0 deletions AUTHORS.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
- Matthias Dittrich ([@matthid](https://github.com/matthid))
- Patrick Stewart ([@patstew](https://github.com/patstew))
- Raphael Nestler ([@rnestler](https://github.com/rnestler))
- Rickard Holmberg ([@rickardraysearch](https://github.com/rickardraysearch))
- Sam Winstanley ([@swinstanley](https://github.com/swinstanley))
- Sean Freitag ([@cowboygneox](https://github.com/cowboygneox))
- Serge Weinstock ([@sweinst](https://github.com/sweinst))
Expand Down
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ This document follows the conventions laid out in [Keep a CHANGELOG][].
derived from a .NET class has a `__namespace__` or `__assembly__`
attribute (#481)
- Fixed conversion of 'float' and 'double' values (#486)
- Fixed 'clrmethod' for python 2 (#492)


## [2.3.0][] - 2017-03-11
Expand Down
43 changes: 42 additions & 1 deletion src/embed_tests/TestRuntime.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using System;
using System;
using NUnit.Framework;
using Python.Runtime;

Expand Down Expand Up @@ -47,5 +47,46 @@ public static void RefCountTest()

Runtime.Runtime.Py_Finalize();
}

[Test]
public static void PyCheck_Iter_PyObject_IsIterable_Test()
{
Runtime.Runtime.Py_Initialize();

// Tests that a python list is an iterable, but not an iterator
var pyList = Runtime.Runtime.PyList_New(0);
Assert.IsFalse(Runtime.Runtime.PyIter_Check(pyList));
Assert.IsTrue(Runtime.Runtime.PyObject_IsIterable(pyList));

// Tests that a python list iterator is both an iterable and an iterator
var pyListIter = Runtime.Runtime.PyObject_GetIter(pyList);
Assert.IsTrue(Runtime.Runtime.PyObject_IsIterable(pyListIter));
Assert.IsTrue(Runtime.Runtime.PyIter_Check(pyListIter));

// Tests that a python float is neither an iterable nor an iterator
var pyFloat = Runtime.Runtime.PyFloat_FromDouble(2.73);
Assert.IsFalse(Runtime.Runtime.PyObject_IsIterable(pyFloat));
Assert.IsFalse(Runtime.Runtime.PyIter_Check(pyFloat));

Runtime.Runtime.Py_Finalize();
}

[Test]
public static void PyCheck_Iter_PyObject_IsIterable_ThreadingLock_Test()
{
Runtime.Runtime.Py_Initialize();

// Create an instance of threading.Lock, which is one of the very few types that does not have the
// TypeFlags.HaveIter set in Python 2. This tests a different code path in PyObject_IsIterable and PyIter_Check.
var threading = Runtime.Runtime.PyImport_ImportModule("threading");
var threadingDict = Runtime.Runtime.PyModule_GetDict(threading);
var lockType = Runtime.Runtime.PyDict_GetItemString(threadingDict, "Lock");
var lockInstance = Runtime.Runtime.PyObject_CallObject(lockType, Runtime.Runtime.PyTuple_New(0));

Assert.IsFalse(Runtime.Runtime.PyObject_IsIterable(lockInstance));
Assert.IsFalse(Runtime.Runtime.PyIter_Check(lockInstance));

Runtime.Runtime.Py_Finalize();
}
}
}
2 changes: 1 addition & 1 deletion src/runtime/pyobject.cs
Original file line number Diff line number Diff line change
Expand Up @@ -802,7 +802,7 @@ public bool IsCallable()
/// </remarks>
public bool IsIterable()
{
return Runtime.PyIter_Check(obj);
return Runtime.PyObject_IsIterable(obj);
}


Expand Down
39 changes: 26 additions & 13 deletions src/runtime/runtime.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using System;
using System;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
Expand Down Expand Up @@ -274,19 +274,17 @@ internal static void Initialize()

Error = new IntPtr(-1);

#if PYTHON3
IntPtr dllLocal = IntPtr.Zero;
if (PythonDll != "__Internal")
{
NativeMethods.LoadLibrary(PythonDll);
dllLocal = NativeMethods.LoadLibrary(PythonDll);
}
_PyObject_NextNotImplemented = NativeMethods.GetProcAddress(dllLocal, "_PyObject_NextNotImplemented");
#if !(MONO_LINUX || MONO_OSX)
if (dllLocal != IntPtr.Zero)
{
NativeMethods.FreeLibrary(dllLocal);
}
#endif
#endif

// Initialize modules that depend on the runtime class.
Expand Down Expand Up @@ -349,8 +347,8 @@ internal static int AtExit()

#if PYTHON3
internal static IntPtr PyBytesType;
internal static IntPtr _PyObject_NextNotImplemented;
#endif
internal static IntPtr _PyObject_NextNotImplemented;

internal static IntPtr PyNotImplemented;
internal const int Py_LT = 0;
Expand Down Expand Up @@ -780,6 +778,21 @@ internal static string PyObject_GetTypeName(IntPtr op)
return Marshal.PtrToStringAnsi(ppName);
}

/// <summary>
/// Test whether the Python object is an iterable.
/// </summary>
internal static bool PyObject_IsIterable(IntPtr pointer)
{
var ob_type = Marshal.ReadIntPtr(pointer, ObjectOffset.ob_type);
#if PYTHON2
long tp_flags = Marshal.ReadInt64(ob_type, TypeOffset.tp_flags);
if ((tp_flags & TypeFlags.HaveIter) == 0)
return false;
#endif
IntPtr tp_iter = Marshal.ReadIntPtr(ob_type, TypeOffset.tp_iter);
return tp_iter != IntPtr.Zero;
}

[DllImport(PythonDll, CallingConvention = CallingConvention.Cdecl)]
internal static extern int PyObject_HasAttrString(IntPtr pointer, string name);

Expand Down Expand Up @@ -1425,17 +1438,17 @@ internal static bool PyTuple_Check(IntPtr ob)
// Python iterator API
//====================================================================

#if PYTHON2
[DllImport(PythonDll, CallingConvention = CallingConvention.Cdecl)]
internal static extern bool PyIter_Check(IntPtr pointer);
#elif PYTHON3
internal static bool PyIter_Check(IntPtr pointer)
{
var ob_type = (IntPtr)Marshal.PtrToStructure(pointer + ObjectOffset.ob_type, typeof(IntPtr));
IntPtr tp_iternext = ob_type + TypeOffset.tp_iternext;
return tp_iternext != null && tp_iternext != _PyObject_NextNotImplemented;
}
var ob_type = Marshal.ReadIntPtr(pointer, ObjectOffset.ob_type);
#if PYTHON2
long tp_flags = Marshal.ReadInt64(ob_type, TypeOffset.tp_flags);
if ((tp_flags & TypeFlags.HaveIter) == 0)
return false;
#endif
IntPtr tp_iternext = Marshal.ReadIntPtr(ob_type, TypeOffset.tp_iternext);
return tp_iternext != IntPtr.Zero && tp_iternext != _PyObject_NextNotImplemented;
}

[DllImport(PythonDll, CallingConvention = CallingConvention.Cdecl)]
internal static extern IntPtr PyIter_Next(IntPtr pointer);
Expand Down
73 changes: 73 additions & 0 deletions src/tests/test_clrmethod.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
# -*- coding: utf-8 -*-

"""Test clrmethod and clrproperty support for calling methods and getting/setting python properties from CLR."""

import Python.Test as Test
import System
import pytest
import clr

class ExampleClrClass(System.Object):
__namespace__ = "PyTest"
def __init__(self):
self._x = 3
@clr.clrmethod(int, [int])
def test(self, x):
return x*2

def get_X(self):
return self._x
def set_X(self, value):
self._x = value
X = clr.clrproperty(int, get_X, set_X)

@clr.clrproperty(int)
def Y(self):
return self._x * 2

def test_set_and_get_property_from_py():
"""Test setting and getting clr-accessible properties from python."""
t = ExampleClrClass()
assert t.X == 3
assert t.Y == 3 * 2
t.X = 4
assert t.X == 4
assert t.Y == 4 * 2

def test_set_and_get_property_from_clr():
"""Test setting and getting clr-accessible properties from the clr."""
t = ExampleClrClass()
assert t.GetType().GetProperty("X").GetValue(t) == 3
assert t.GetType().GetProperty("Y").GetValue(t) == 3 * 2
t.GetType().GetProperty("X").SetValue(t, 4)
assert t.GetType().GetProperty("X").GetValue(t) == 4
assert t.GetType().GetProperty("Y").GetValue(t) == 4 * 2


def test_set_and_get_property_from_clr_and_py():
"""Test setting and getting clr-accessible properties alternatingly from the clr and from python."""
t = ExampleClrClass()
assert t.GetType().GetProperty("X").GetValue(t) == 3
assert t.GetType().GetProperty("Y").GetValue(t) == 3 * 2
assert t.X == 3
assert t.Y == 3 * 2
t.GetType().GetProperty("X").SetValue(t, 4)
assert t.GetType().GetProperty("X").GetValue(t) == 4
assert t.GetType().GetProperty("Y").GetValue(t) == 4 * 2
assert t.X == 4
assert t.Y == 4 * 2
t.X = 5
assert t.GetType().GetProperty("X").GetValue(t) == 5
assert t.GetType().GetProperty("Y").GetValue(t) == 5 * 2
assert t.X == 5
assert t.Y == 5 * 2

def test_method_invocation_from_py():
"""Test calling a clr-accessible method from python."""
t = ExampleClrClass()
assert t.test(41) == 41*2

def test_method_invocation_from_clr():
"""Test calling a clr-accessible method from the clr."""
t = ExampleClrClass()
assert t.GetType().GetMethod("test").Invoke(t, [37]) == 37*2