Specify Encoding.UTF8 when marshaling native runtime string. If not, string construct...
authorJonathan Chambers <joncham@gmail.com>
Thu, 11 May 2017 13:30:23 +0000 (09:30 -0400)
committerMarek Safar <marek.safar@gmail.com>
Thu, 11 May 2017 17:21:43 +0000 (19:21 +0200)
mcs/class/corlib/Mono/RuntimeMarshal.cs

index 5c997cd677ac36fc30e04f9f4f2ea25d99e32d26..28124b21aaf4341cf93686fa5dbd05f9d84e9658 100644 (file)
@@ -7,7 +7,20 @@ namespace Mono {
                internal static string PtrToUtf8String (IntPtr ptr)
                {
                        unsafe {
-                               return new String ((sbyte*)ptr);
+                               if (ptr == IntPtr.Zero)
+                                       return string.Empty;
+
+                               byte* bytes = (byte*)ptr;
+                               int length = 0;
+
+                               try {
+                                       while (bytes++ [0] != 0)
+                                               length++;
+                               } catch (NullReferenceException) {
+                                       throw new ArgumentOutOfRangeException ("ptr", "Value does not refer to a valid string.");
+                               }
+
+                               return new String ((sbyte*)ptr, 0, length, System.Text.Encoding.UTF8);
                        }
                }