public static void TestUTF8Marshalling(string chars, byte[] expected) { IntPtr pString = IntPtr.Zero; try { pString = Marshal.StringToCoTaskMemUTF8(chars); string utf8String = Marshal.PtrToStringUTF8(pString); Assert.Equal(chars, utf8String); } finally { if (pString != IntPtr.Zero) { Marshal.ZeroFreeCoTaskMemUTF8(pString); } } }