Skip to content

Instantly share code, notes, and snippets.

@jefgen
Created March 24, 2021 23:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jefgen/1730a831eebcee7fba95cf13dd46df5c to your computer and use it in GitHub Desktop.
Save jefgen/1730a831eebcee7fba95cf13dd46df5c to your computer and use it in GitHub Desktop.
HSTRING wrapper class
public class HSTRING
{
public IntPtr myString;
public HSTRING()
{
myString = IntPtr.Zero;
}
public HSTRING(IntPtr s)
{
myString = s;
}
public HSTRING(string s)
{
Marshal.ThrowExceptionForHR(WindowsCreateString(s, s.Length, out IntPtr h));
myString = h;
}
~HSTRING()
{
Marshal.ThrowExceptionForHR(WindowsDeleteString(myString));
}
public static IntPtr FromString(string s)
{
Marshal.ThrowExceptionForHR(WindowsCreateString(s, s.Length, out IntPtr h));
return h;
}
public static string ToString(IntPtr ptr)
{
long stringLength;
IntPtr stringBackingBuffer = WindowsGetStringRawBuffer(ptr, out stringLength);
return Marshal.PtrToStringUni(stringBackingBuffer, Convert.ToInt32(stringLength));
}
public static void Delete(IntPtr s)
{
Marshal.ThrowExceptionForHR(WindowsDeleteString(s));
}
[DllImport("api-ms-win-core-winrt-string-l1-1-0.dll", CallingConvention = CallingConvention.StdCall, ExactSpelling = true)]
private static extern int WindowsCreateString([MarshalAs(UnmanagedType.LPWStr)] string sourceString, int length, out IntPtr hstring);
[DllImport("api-ms-win-core-winrt-string-l1-1-0.dll", CallingConvention = CallingConvention.StdCall, ExactSpelling = true)]
private static extern int WindowsDeleteString(IntPtr hstring);
[DllImport("api-ms-win-core-winrt-string-l1-1-0.dll", CallingConvention = CallingConvention.StdCall, ExactSpelling = true)]
private static extern IntPtr WindowsGetStringRawBuffer(IntPtr hstring, out long size);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment