public static IntPtr StringToHeap(string s, int index, int count, Encoding encoding) { if (s == null) { return(IntPtr.Zero); } if (encoding == null) { throw new ArgumentNullException("encoding"); } int maxByteCount = encoding.GetMaxByteCount(1); char[] charArray = s.ToCharArray(index, count); byte[] numArray = new byte[encoding.GetByteCount(charArray) + maxByteCount]; if (encoding.GetBytes(charArray, 0, (int)charArray.Length, numArray, 0) != (int)numArray.Length - maxByteCount) { throw new NotSupportedException("encoding.GetBytes() doesn't equal encoding.GetByteCount()!"); } IntPtr intPtr = UnixMarshal.AllocHeap((long)((int)numArray.Length)); if (intPtr == IntPtr.Zero) { throw new UnixIOException(Errno.ENOMEM); } bool flag = false; try { Marshal.Copy(numArray, 0, intPtr, (int)numArray.Length); flag = true; } finally { if (!flag) { UnixMarshal.FreeHeap(intPtr); } } return(intPtr); }