一、概述
32位寬字符串,前面32位為長度,尾部以0結束
二、相關定義
BSTR (又稱Basic 類型字符串)
LPOLESTR
相關宏定義:
typedef unsigned short wchar_t; (unsigned short為兩字節)
typedef wchar_t WCHAR;
typedef WCHAR OLECHAR; (Win32)
typedef OLECHAR* BSTR;
typedef /* [string] */ OLECHAR __RPC_FAR *LPOLESTR;
三、使用
1.分配
// Create BSTR containing "Text"
bs = SysAllocString(L"Text")
// Create BSTR containing "Te"
bs = SysAllocStringLen(L"Text", 2)
// Create BSTR containing "Text" followed by \0 and a junk character
bs = SysAllocStringLen(L"Text", 6)
// Reallocate BSTR bs as "NewText" 重新賦值
f = SysReAllocString(&bs, "NewText");
2.長度
// Get character length of string.
cch = SysStringLen(bs);
3.釋放
// Deallocate a string.
SysFreeString(bs);
四、轉換問題
1 使用_bstr_t
BSTR tmpBStr;
m_pObject1->get_ObjectString(&tmpBStr);
_bstr_t tmpbstr(tmpBStr, FALSE); //將得到的BSTR作為構造函數參數
SetDlgItemText(IDC_CURPROPVAL, tmpbstr);
注意: 直接賦值轉換,會引發內存洩漏
BSTR tmpBStr;
m_pObject1->get_ObjectString(&tmpBStr);
_bstr_t tmpbstr;
tmpbstr= tmpBStr; //Caution: 內存洩漏參數
SetDlgItemText(IDC_CURPROPVAL, tmpbstr);
2 使用T2COLE、T2OLE等
#include<afxpriv.h>
在轉換前需要添加宏
USES_CONVERSION
#define USES_CONVERSION int _convert = 0; \ _convert;\ UINT _acp = GetACP();\ _acp;\ LPCWSTR _lpw = NULL;\ _lpw;\ LPCSTR _lpa = NULL;\ _lpa
這個宏提供了一些臨時變量供轉化用
看一下其在單字節字符集時的宏定義
#define T2COLE(lpa) A2CW(lpa) #define T2OLE(lpa) A2W(lpa) #define OLE2CT(lpo) W2CA(lpo) #define OLE2T(lpo) W2A(lpo) #define A2CW(lpa) ((LPCWSTR)A2W(lpa)) #define W2CA(lpw) ((LPCSTR)W2A(lpw)) #define A2W(lpa) (\ ((_lpa = lpa) == NULL) ? NULL : (\ _convert = (lstrlenA(_lpa)+1),\ ATLA2WHELPER((LPWSTR) alloca(_convert*2), _lpa, _convert))) #define W2A(lpw) (\ ((_lpw = lpw) == NULL) ? NULL : (\ _convert = (lstrlenW(_lpw)+1)*2,\ ATLW2AHELPER((LPSTR) alloca(_convert), _lpw, _convert))) LPSTR AFXAPI AfxW2AHelper(LPSTR lpa, LPCWSTR lpw, int nChars) { if (lpw == NULL) return NULL; ASSERT(lpa != NULL); // verify that no illegal character present // since lpa was allocated based on the size of lpw // don''t worry about the number of chars lpa[0] = ''\0''; VERIFY(WideCharToMultiByte(CP_ACP, 0, lpw, -1, lpa, nChars, NULL, NULL)); return lpa; } LPWSTR AFXAPI AfxA2WHelper(LPWSTR lpw, LPCSTR lpa, int nChars) { if (lpa == NULL) return NULL; ASSERT(lpw != NULL); // verify that no illegal character present // since lpw was allocated based on the size of lpa // don''t worry about the number of chars lpw[0] = ''\0''; VERIFY(MultiByteToWideChar(CP_ACP, 0, lpa, -1, lpw, nChars)); return lpw; }
3 .CString 對轉化的支持
//m_cstrCaption是一個CString 對象。
BSTR bstrCaption =m_cstrCaption.AllocSysString();
FireChange(&bstrCaption,&m_lAlignment);
::SysFreeString(bstrCaption);
(全文完)