public static string PtrToString(IntPtr p, Encoding encoding) { if (p == IntPtr.Zero) { return(null); } if (encoding == null) { throw new ArgumentNullException("encoding"); } int stringByteLength = UnixMarshal.GetStringByteLength(p, encoding); string str = new string((void *)p, 0, stringByteLength, encoding); stringByteLength = str.Length; while (stringByteLength > 0 && str[stringByteLength - 1] == 0) { stringByteLength--; } if (stringByteLength == str.Length) { return(str); } return(str.Substring(0, stringByteLength)); }