@@ -1725,7 +1725,20 @@ internal static IntPtr PyUnicode_FromString(string s)
17251725 return PyUnicode_FromUnicode( s , ( s . Length ) ) ;
17261726 }
17271727
1728- internal unsafe static string GetManagedString ( IntPtr op )
1728+ /// <summary>
1729+ /// Function to access the internal PyUnicode/PyString object and
1730+ /// convert it to a managed string with the correct encoding.
1731+ /// </summary>
1732+ /// <remarks>
1733+ /// We can't easily do this through through the CustomMarshaler's on
1734+ /// the returns because will have access to the IntPtr but not size.
1735+ /// <para />
1736+ /// For PyUnicodeType, we can't convert with Marshal.PtrToStringUni
1737+ /// since it only works for UCS2.
1738+ /// </remarks>
1739+ /// <param name="op">PyStringType or PyUnicodeType object to convert</param>
1740+ /// <returns>Managed String</returns>
1741+ internal static string GetManagedString ( IntPtr op )
17291742 {
17301743 IntPtr type = PyObject_TYPE( op ) ;
17311744
@@ -1741,18 +1754,15 @@ internal unsafe static string GetManagedString(IntPtr op)
17411754
17421755 if ( type = = Runtime . PyUnicodeType )
17431756 {
1744- #if UCS4
1745- IntPtr p = Runtime. PyUnicode_AsUnicode( op) ;
1746- int length = Runtime. PyUnicode_GetSize( op ) ;
1747- int size = length * 4 ;
1748- byte [ ] buffer = new byte [ size ] ;
1757+ Encoding encoding = UCS == 2 ? Encoding. Unicode : Encoding. UTF32;
1758+
1759+ IntPtr p = PyUnicode_AsUnicode( op) ;
1760+ int length = PyUnicode_GetSize( op ) ;
1761+
1762+ int size = length * UCS;
1763+ var buffer = new byte [ size ] ;
17491764 Marshal . Copy ( p , buffer , 0 , size ) ;
1750- return Encoding . UTF32 . GetString ( buffer , 0 , size ) ;
1751- #elif UCS2
1752- IntPtr p = Runtime . PyUnicode_AsUnicode ( op ) ;
1753- int length = Runtime. PyUnicode_GetSize( op ) ;
1754- return Marshal . PtrToStringUni ( p , length ) ;
1755- #endif
1765+ return encoding . GetString ( buffer , 0 , size ) ;
17561766 }
17571767
17581768 return null ;
0 commit comments