public Utf8StringHandle(string str) : base(true) { IntPtr buffer; if (str == null) { buffer = IntPtr.Zero; } else { if (str.Length == 0) { buffer = Marshal.AllocHGlobal(1); unsafe { *(byte *)buffer = 0; } } else { var strlen = Utf8.GetByteCount(str); var strBuffer = new byte[strlen + 1]; Utf8.GetBytes(str, 0, str.Length, strBuffer, 0); buffer = Marshal.AllocHGlobal(strBuffer.Length); Marshal.Copy(strBuffer, 0, buffer, strBuffer.Length); } } SetHandle(buffer); }