也谈UTF-8转换为Unicode方法

几天前需要做UTF-8和GB的转换,主要是因为进程间通信需要使用这种模式。他使用C#开发的程序需要和我VC++写的程序之间进行通信的时候,发现他给我传过来的数据是UTF-8类型的。因此在CSDN中搜索UTF-8和unicode的转换方法,发现查找到的文章方法都比较复杂,所以就开始在MSDN中查找。最终根据查找到的资料,写了如下的代码进行UTF-8和Unicode的转化。

BSTR UTF2GB(LPCSTR lp, int nLen)
{
   BSTR str = NULL;
   int nConvertedLen = MultiByteToWideChar(CP_UTF8, 0, lp,
     nLen, NULL, NULL);
 
   // BUG FIX #1 (from Q241857): only subtract 1 from
   // the length if the source data is nul-terminated
   if (nLen == -1)
      nConvertedLen--;
 
   str = ::SysAllocStringLen(NULL, nConvertedLen);
   if (str != NULL)
   {
     MultiByteToWideChar(CP_UTF8, 0, lp, nLen, str, nConvertedLen);
   }
   return str;
}

你可能感兴趣的:(开发)