public static void StringToCoTaskMemAuto() { String s = null; // passing null string should return 0 Assert.Equal(0, (long)Marshal.StringToCoTaskMemAuto(s)); s = "Hello World"; IntPtr ptr = Marshal.StringToCoTaskMemAuto(s); // make sure the native memory is correctly laid out for (int i = 0; i < s.Length; i++) { char c = (char)Marshal.ReadInt16(IntPtr.Add(ptr, i << 1)); Assert.Equal(s[i], c); } // make sure if we convert back to string we get the same value String s2 = Marshal.PtrToStringAuto(ptr); Assert.Equal(s, s2); // free the native memory Marshal.FreeCoTaskMem(ptr); }
public static void PtrToStringAutoWithLength() { Assert.Throws <ArgumentNullException>(() => Marshal.PtrToStringAuto(IntPtr.Zero, 0)); String s = "Hello World"; int len = 5; IntPtr ptr = Marshal.StringToCoTaskMemAuto(s); String s2 = Marshal.PtrToStringAuto(ptr, len); Assert.Equal(s.Substring(0, len), s2); Marshal.FreeCoTaskMem(ptr); }
public static void StringToCoTaskMemAuto_PtrToStringAuto_ReturnsExpected() { string s = "Hello World"; int len = 5; IntPtr ptr = Marshal.StringToCoTaskMemAuto(s); try { string actual = Marshal.PtrToStringAuto(ptr, len); Assert.Equal(s.Substring(0, len), actual); } finally { Marshal.FreeCoTaskMem(ptr); } }