Skip to content
This repository has been archived by the owner on Mar 30, 2019. It is now read-only.

Commit

Permalink
Fixed PtrToStringAnsi and PtrToStringUni to correctly return null-ter…
Browse files Browse the repository at this point in the history
…minating string instead of always returning string with maxLength chars
  • Loading branch information
abenedik committed Nov 25, 2016
1 parent ab6fed4 commit 5dfcc33
Showing 1 changed file with 11 additions and 3 deletions.
14 changes: 11 additions & 3 deletions Source/SharpDX/Utilities.cs
Original file line number Diff line number Diff line change
Expand Up @@ -502,7 +502,11 @@ public unsafe static void FreeMemory(IntPtr alignedBuffer)
/// <returns>The converted string.</returns>
public static string PtrToStringAnsi(IntPtr pointer, int maxLength)
{
return Marshal.PtrToStringAnsi(pointer, maxLength);
string managedString = Marshal.PtrToStringAnsi(pointer); // copy null-terminating unmanaged text from pointer to a managed string
if (managedString != null && managedString.Length > maxLength)
managedString = managedString.Substring(0, maxLength);

return managedString;
}

/// <summary>
Expand All @@ -513,10 +517,14 @@ public static string PtrToStringAnsi(IntPtr pointer, int maxLength)
/// <returns>The converted string.</returns>
public static string PtrToStringUni(IntPtr pointer, int maxLength)
{
return Marshal.PtrToStringUni(pointer, maxLength);
string managedString = Marshal.PtrToStringUni(pointer); // copy null-terminating unmanaged text from pointer to a managed string
if (managedString != null && managedString.Length > maxLength)
managedString = managedString.Substring(0, maxLength);

return managedString;
}

/// <summary>
/// <summary>
/// Copies the contents of a managed String into unmanaged memory, converting into ANSI format as it copies.
/// </summary>
/// <param name="s">A managed string to be copied.</param>
Expand Down

0 comments on commit 5dfcc33

Please sign in to comment.