@@ -1725,7 +1725,20 @@ internal static IntPtr PyUnicode_FromString(string s)
1725
1725
return PyUnicode_FromUnicode( s , ( s . Length ) ) ;
1726
1726
}
1727
1727
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 )
1729
1742
{
1730
1743
IntPtr type = PyObject_TYPE( op ) ;
1731
1744
@@ -1741,18 +1754,15 @@ internal unsafe static string GetManagedString(IntPtr op)
1741
1754
1742
1755
if ( type = = Runtime . PyUnicodeType )
1743
1756
{
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 ] ;
1749
1764
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 ) ;
1756
1766
}
1757
1767
1758
1768
return null ;
0 commit comments