Skip to content

Commit eec8893

Browse files
committed
Add function of passing an arbitrary .NET object as the value of an
attribute of PyObject by dynamic type
1 parent 58bc902 commit eec8893

File tree

3 files changed

+37
-3
lines changed

3 files changed

+37
-3
lines changed

AUTHORS.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,3 +39,4 @@
3939
- ([@rico-chet](https://github.com/rico-chet))
4040
- ([@rmadsen-ks](https://github.com/rmadsen-ks))
4141
- ([@stonebig](https://github.com/stonebig))
42+
- Wenguang Yang ([@yagweb](https://github.com/yagweb))

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ This document follows the conventions laid out in [Keep a CHANGELOG][].
1414
- Added XML Documentation (#349)
1515
- Added Embedded tests on Appveyor (#353)
1616
- Added PY3 settings to configuration-manager (#346)
17+
- Added function of passing an arbitrary .NET object as the value of an attribute of PyObject (#370)
1718

1819
### Changed
1920

src/runtime/pyobject.cs

Lines changed: 35 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -181,7 +181,31 @@ public bool HasAttr(PyObject name)
181181
{
182182
return Runtime.PyObject_HasAttr(obj, name.obj) != 0;
183183
}
184-
184+
185+
/// <summary>
186+
/// GetAttr Method For Dynamic Type
187+
/// </summary>
188+
/// <remarks>
189+
/// Returns the named attribute of the Python object, or raises a
190+
/// PythonException if the attribute access fails.
191+
/// </remarks>
192+
public object GetAttrDynamic(string name)
193+
{
194+
IntPtr op = Runtime.PyObject_GetAttrString(obj, name);
195+
if (op == IntPtr.Zero)
196+
{
197+
throw new PythonException();
198+
}
199+
if (ManagedType.IsManagedType(op))
200+
{
201+
ManagedType managedMethod = ManagedType.GetManagedObject(op);
202+
if (managedMethod is CLRObject)
203+
{
204+
return ((CLRObject)managedMethod).inst;
205+
}
206+
}
207+
return CheckNone(new PyObject(op));
208+
}
185209

186210
/// <summary>
187211
/// GetAttr Method
@@ -891,7 +915,7 @@ public override bool TryGetMember(GetMemberBinder binder, out object result)
891915
{
892916
if (this.HasAttr(binder.Name))
893917
{
894-
result = CheckNone(this.GetAttr(binder.Name));
918+
result = this.GetAttrDynamic(binder.Name);
895919
return true;
896920
}
897921
else
@@ -904,7 +928,15 @@ public override bool TrySetMember(SetMemberBinder binder, object value)
904928
{
905929
if (this.HasAttr(binder.Name))
906930
{
907-
this.SetAttr(binder.Name, (PyObject)value);
931+
if (value is PyObject)
932+
{
933+
this.SetAttr(binder.Name, (PyObject)value);
934+
}
935+
else
936+
{
937+
var ptr = CLRObject.GetInstHandle(value, value.GetType());
938+
this.SetAttr(binder.Name, new PyObject(ptr));
939+
}
908940
return true;
909941
}
910942
else

0 commit comments

Comments
 (0)