99using System . Text ;
1010
1111using Python . Runtime . Native ;
12+ using System . Linq ;
1213
1314namespace Python . Runtime
1415{
@@ -508,7 +509,6 @@ internal static bool ToManagedValue(BorrowedReference value, Type obType,
508509 // Method bindings will be handled below along with actual Python callables
509510 if ( mt is not MethodBinding )
510511 {
511- // shouldn't happen
512512 return false ;
513513 }
514514 }
@@ -549,7 +549,7 @@ internal static bool ToManagedValue(BorrowedReference value, Type obType,
549549 return ToEnum ( value , obType , out result , setError , out usedImplicit ) ;
550550 }
551551
552- if ( Runtime . PyCallable_Check ( value ) != 0 && TryConvertToDelegate ( value , obType , out result ) )
552+ if ( TryConvertToDelegate ( value , obType , out result ) )
553553 {
554554 return true ;
555555 }
@@ -742,7 +742,7 @@ internal static bool TryConvertToDelegate(BorrowedReference pyValue, Type delega
742742 {
743743 result = null ;
744744
745- if ( ! typeof ( MulticastDelegate ) . IsAssignableFrom ( delegateType ) )
745+ if ( ! typeof ( MulticastDelegate ) . IsAssignableFrom ( delegateType ) || Runtime . PyCallable_Check ( pyValue ) == 0 )
746746 {
747747 return false ;
748748 }
@@ -755,24 +755,22 @@ internal static bool TryConvertToDelegate(BorrowedReference pyValue, Type delega
755755 var code = string . Empty ;
756756 var types = delegateType . GetGenericArguments ( ) ;
757757
758- using var _ = Py . GIL ( ) ;
759758 using var locals = new PyDict ( ) ;
760759 try
761760 {
762- for ( var i = 0 ; i < types . Length ; i ++ )
763- {
764- var iString = i . ToString ( CultureInfo . InvariantCulture ) ;
765- code += $ ",t{ iString } ";
766- locals . SetItem ( $ "t{ iString } ", types [ i ] . ToPython ( ) ) ;
767- }
768-
769761 using var pyCallable = new PyObject ( pyValue ) ;
770762 locals . SetItem ( "pyCallable" , pyCallable ) ;
771763
772764 if ( types . Length > 0 )
773765 {
766+ code = string . Join ( ',' , types . Select ( ( type , i ) =>
767+ {
768+ var t = $ "t{ i } ";
769+ locals . SetItem ( t , type . ToPython ( ) ) ;
770+ return t ;
771+ } ) ) ;
774772 var name = delegateType . Name . Substring ( 0 , delegateType . Name . IndexOf ( '`' ) ) ;
775- code = $ "from System import { name } ; delegate = { name } [{ code . Substring ( 1 ) } ](pyCallable)";
773+ code = $ "from System import { name } ; delegate = { name } [{ code } ](pyCallable)";
776774 }
777775 else
778776 {
0 commit comments