111,097
社区成员




Function StringToHeap(ByVal s As String, ByVal encoding As System.Text.Encoding) As IntPtr
If encoding Is Nothing Then
Return ""
End If
Dim min_byte_count As Integer = encoding.GetMaxByteCount(1)
Dim copy() As Char = s.ToCharArray()
Dim marshal(encoding.GetByteCount(copy) + min_byte_count) As Byte
Dim bytes_copied As Integer = encoding.GetBytes(copy, 0, copy.Length, marshal, 0)
If bytes_copied <> marshal.Length - min_byte_count Then
Throw New NotSupportedException("encoding.GetBytes() doesn't equal encoding.GetByteCount()!")
End If
Dim mem As IntPtr = System.Runtime.InteropServices.Marshal.AllocCoTaskMem(marshal.Length)
If mem = IntPtr.Zero Then
Throw New OutOfMemoryException()
End If
Dim copied As Boolean = False
Try
System.Runtime.InteropServices.Marshal.Copy(marshal, 0, mem, marshal.Length)
copied = True
Finally
If copied = False Then
System.Runtime.InteropServices.Marshal.FreeCoTaskMem(mem)
End If
End Try
Return mem
End Function