Created
March 24, 2021 23:46
-
-
Save jefgen/1730a831eebcee7fba95cf13dd46df5c to your computer and use it in GitHub Desktop.
HSTRING wrapper class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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