字串: 怎樣在ANSI 和 UNICODE間做轉換 (轉)

worldblog發表於2007-12-14
字串: 怎樣在ANSI 和 UNICODE間做轉換 (轉)[@more@]

字串: 怎樣在ANSI 和 UNICODE間做轉換

問題: 怎樣在ANSI 和 UNICODE間做轉換?

答案:

這個答案啟發自 Yves M貼出的一張回覆(reply)


ANSI 到 UNICODE:


這個轉換用MultiByteToWChar()完成

程式碼:
--------------------------------------------------------------------------------
  char *ansistr = "Hello";
  int a = lstrlenA(ansistr)+1;
  BSTR unicodestr = SysAllocStringLen(NULL, 2*a);
  MultiByteToWideChar(CP_ACP, 0, ansistr, a, unicodestr, a);
  AfxMessageBox(CString(unicodestr), MB_OK, 0); //displays "Hello"
  //... when done, free the BSTR
  SyreeString(unicodestr);
--------------------------------------------------------------------------------

UNICODE 到 ANSI:

UNICODE大多數情況下被OLE函式返回, 像這個

程式碼:
--------------------------------------------------------------------------------
HRESULT SomeOLEFunction(BSTR &bstr)
{
  bstr = ::SysAllocString(L"Hello");
  return S_OK;
}
--------------------------------------------------------------------------------

這個轉換用WideCharToMultiByte()函式完成

程式碼:
--------------------------------------------------------------------------------
  BSTR unicodestr;
  SomeOLEFunction(unicodestr);
  int a = SysStringLen(unicodestr)+1;
  char *ansistr = new char[a];
  WideCharToMultiByte(CP_ACP,
  0,
  unicodestr,
  -1,
  ansistr,
  a,
  NULL,
  NULL);
  AfxMessageBox(ansistr, MB_OK, 0); // will display "Hello"
  //...use the strings, then free their memory:
  delete[] ansistr;
  SysFreeString(unicodestr);
--------------------------------------------------------------------------------


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/10752043/viewspace-993442/,如需轉載,請註明出處,否則將追究法律責任。

相關文章