Commit 3ee232b8 authored by Martin Finkel's avatar Martin Finkel

Utf8 extensions: Use AllocHGlobal, not AllocCoTaskMem

parent d099a8fb
...@@ -118,11 +118,20 @@ namespace LibVLCSharp.Shared.Helpers ...@@ -118,11 +118,20 @@ namespace LibVLCSharp.Shared.Helpers
if (str == null) if (str == null)
return IntPtr.Zero; return IntPtr.Zero;
byte[] utf8bytes = Encoding.UTF8.GetBytes(str); byte[] bytes = Encoding.UTF8.GetBytes(str);
IntPtr ptr = Marshal.AllocCoTaskMem(utf8bytes.Length + 1); var nativeString = Marshal.AllocHGlobal(bytes.Length + 1);
Marshal.Copy(utf8bytes, 0, ptr, utf8bytes.Length); try
Marshal.WriteByte(ptr, utf8bytes.Length, 0); {
return ptr; Marshal.Copy(bytes, 0, nativeString, bytes.Length);
Marshal.WriteByte(nativeString, bytes.Length, 0);
}
catch (Exception)
{
Marshal.FreeHGlobal(nativeString);
throw;
}
return nativeString;
} }
/// <summary> /// <summary>
...@@ -137,19 +146,18 @@ namespace LibVLCSharp.Shared.Helpers ...@@ -137,19 +146,18 @@ namespace LibVLCSharp.Shared.Helpers
if (nativeString == IntPtr.Zero) if (nativeString == IntPtr.Zero)
return null; return null;
var bytes = new List<byte>(); var length = 0;
for (int offset = 0; ; offset++)
while (Marshal.ReadByte(nativeString, length) != 0)
{ {
byte b = Marshal.ReadByte(nativeString, offset); length++;
if (b == 0)
break;
else bytes.Add(b);
} }
var str = Encoding.UTF8.GetString(bytes.ToArray(), 0, bytes.Count); byte[] buffer = new byte[length];
Marshal.Copy(nativeString, buffer, 0, buffer.Length);
if (libvlcFree) if (libvlcFree)
MarshalUtils.LibVLCFree(ref nativeString); MarshalUtils.LibVLCFree(ref nativeString);
return str; return Encoding.UTF8.GetString(buffer, 0, buffer.Length);
} }
} }
} }
\ No newline at end of file
...@@ -448,12 +448,6 @@ namespace LibVLCSharp.Shared.Helpers ...@@ -448,12 +448,6 @@ namespace LibVLCSharp.Shared.Helpers
ptr = IntPtr.Zero; ptr = IntPtr.Zero;
} }
internal static void Free(params IntPtr[] ptrs)
{
foreach (var ptr in ptrs)
Marshal.FreeHGlobal(ptr);
}
/// <summary> /// <summary>
/// Performs the native call, frees the ptrs and returns the result /// Performs the native call, frees the ptrs and returns the result
/// </summary> /// </summary>
...@@ -490,6 +484,12 @@ namespace LibVLCSharp.Shared.Helpers ...@@ -490,6 +484,12 @@ namespace LibVLCSharp.Shared.Helpers
Free(ptrs); Free(ptrs);
} }
} }
private static void Free(params IntPtr[] ptrs)
{
foreach (var ptr in ptrs)
Marshal.FreeHGlobal(ptr);
}
} }
[AttributeUsage(AttributeTargets.Method)] [AttributeUsage(AttributeTargets.Method)]
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment