public static void CopyStringToHGlobal(string s, IntPtr data, int bufferSize)
{
if (s == null)
throw new ArgumentNullException("s");
if (data == null)
throw new ArgumentNullException("data");
if (bufferSize < 0)
throw new ArgumentOutOfRangeException("bufferSize");
byte[] stringData = System.Text.Encoding.Unicode.GetBytes(s);
if (bufferSize < stringData.Length + 2)
throw new ArgumentException("The encoded string does not fit in the buffer.");
Marshal.Copy(stringData, 0, data, stringData.Length);
Marshal.WriteInt16(data, stringData.Length, 0);
}