diff --git a/CHANGELOG.md b/CHANGELOG.md index 3cc571ad4..0760f0993 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +26,7 @@ This document follows the conventions laid out in [Keep a CHANGELOG][]. - When calling C# from Python, enable passing argument of any type to a parameter of C# type `object` by wrapping it into `PyObject` instance. ([#881][i881]) - Added support for kwarg parameters when calling .NET methods from Python - Changed method for finding MSBuild using vswhere +- Allow conversion to C# object in PyObject.As2 ### Fixed diff --git a/src/embed_tests/TestConverter.cs b/src/embed_tests/TestConverter.cs index 078f4c0f8..caec9aa7f 100644 --- a/src/embed_tests/TestConverter.cs +++ b/src/embed_tests/TestConverter.cs @@ -67,5 +67,15 @@ public void RawPyObjectProxy() var proxiedHandle = pyObjectProxy.GetAttr("Handle").As(); Assert.AreEqual(pyObject.Handle, proxiedHandle); } + + [Test] + public void ConvertToObject() + { + object pyInt = new PyInt(12).As2(); + Assert.AreSame(pyInt.GetType(), typeof(int)); + + object pyString = new PyString("hello").As2(); + Assert.AreSame(pyString.GetType(), typeof(string)); + } } } diff --git a/src/runtime/pyobject.cs b/src/runtime/pyobject.cs index 37d53eeec..e47463157 100644 --- a/src/runtime/pyobject.cs +++ b/src/runtime/pyobject.cs @@ -168,6 +168,20 @@ public T As() return (T)result; } + public T As2() + { + if (typeof(T) == typeof(PyObject)) + { + return (T)(this as object); + } + object result; + if (!Converter.ToManaged(obj, typeof(T), out result, false)) + { + throw new InvalidCastException("cannot convert object to target type"); + } + return (T)result; + } + /// /// Dispose Method