Skip to content

Commit 7951d49

Browse files
committed
use new function instead
1 parent 007e5dd commit 7951d49

File tree

3 files changed

+17
-3
lines changed

3 files changed

+17
-3
lines changed

CHANGELOG.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ This document follows the conventions laid out in [Keep a CHANGELOG][].
2626
- 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])
2727
- Added support for kwarg parameters when calling .NET methods from Python
2828
- Changed method for finding MSBuild using vswhere
29-
- Allow conversion to C# object in PyObject.As<object>
29+
- Allow conversion to C# object in PyObject.As2<object>
3030

3131
### Fixed
3232

src/embed_tests/TestConverter.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -71,10 +71,10 @@ public void RawPyObjectProxy()
7171
[Test]
7272
public void ConvertToObject()
7373
{
74-
object pyInt = new PyInt(12).As<object>();
74+
object pyInt = new PyInt(12).As2<object>();
7575
Assert.AreSame(pyInt.GetType(), typeof(int));
7676

77-
object pyString = new PyString("hello").As<object>();
77+
object pyString = new PyString("hello").As2<object>();
7878
Assert.AreSame(pyString.GetType(), typeof(string));
7979
}
8080
}

src/runtime/pyobject.cs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -155,6 +155,20 @@ public object AsManagedObject(Type t)
155155
/// value of the Python object.
156156
/// </remarks>
157157
public T As<T>()
158+
{
159+
if (typeof(T) == typeof(PyObject) || typeof(T) == typeof(object))
160+
{
161+
return (T)(this as object);
162+
}
163+
object result;
164+
if (!Converter.ToManaged(obj, typeof(T), out result, false))
165+
{
166+
throw new InvalidCastException("cannot convert object to target type");
167+
}
168+
return (T)result;
169+
}
170+
171+
public T As2<T>()
158172
{
159173
if (typeof(T) == typeof(PyObject))
160174
{

0 commit comments

Comments
 (0)