OLE字符串
一、概述
32位宽字符串,前面32位为长度,尾部以0结束
二、相关定义
BSTR (又称Basic 类型字符串)
LPOLESTR
相关宏定义:
1 typedef unsigned short wchar_t; (unsigned short为两字节) 2 typedef wchar_t WCHAR; 3 typedef WCHAR OLECHAR; (Win32) 4 typedef OLECHAR* BSTR; 5 typedef /* [string] */ OLECHAR __RPC_FAR *LPOLESTR;
三、使用
1.分配
1 // Create BSTR containing "Text" 2 bs = SysAllocString(L"Text") 3 4 // Create BSTR containing "Te" 5 bs = SysAllocStringLen(L"Text", 2) 6 // Create BSTR containing "Text" followed by \0 and a junk character 7 bs = SysAllocStringLen(L"Text", 6) 8 9 // Reallocate BSTR bs as "NewText" 重新赋值 10 f = SysReAllocString(&bs, "NewText");
2.长度
1 // Get character length of string. 2 cch = SysStringLen(bs);
3.释放
1 // Deallocate a string. 2 SysFreeString(bs);
四、转换问题
1 使用_bstr_t
1 BSTR tmpBStr; 2 m_pObject1->get_ObjectString(&tmpBStr); 3 _bstr_t tmpbstr(tmpBStr, FALSE); //将得到的BSTR作为构造函数参数 4 SetDlgItemText(IDC_CURPROPVAL, tmpbstr);
注意: 直接赋值转换,会引发内存泄漏
1 BSTR tmpBStr; 2 m_pObject1->get_ObjectString(&tmpBStr); 3 _bstr_t tmpbstr; 4 tmpbstr= tmpBStr; //Caution: 内存泄漏参数 5 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
这个宏提供了一些临时变量供转化用
看一下其在单字节字符集时的宏定义
1 #define T2COLE(lpa) A2CW(lpa) 2 #define T2OLE(lpa) A2W(lpa) 3 #define OLE2CT(lpo) W2CA(lpo) 4 #define OLE2T(lpo) W2A(lpo) 5 6 #define A2CW(lpa) ((LPCWSTR)A2W(lpa)) 7 #define W2CA(lpw) ((LPCSTR)W2A(lpw)) 8 9 #define A2W(lpa) (\ 10 ((_lpa = lpa) == NULL) ? NULL : (\ 11 _convert = (lstrlenA(_lpa)+1),\ 12 ATLA2WHELPER((LPWSTR) alloca(_convert*2), _lpa, _convert))) 13 14 #define W2A(lpw) (\ 15 ((_lpw = lpw) == NULL) ? NULL : (\ 16 _convert = (lstrlenW(_lpw)+1)*2,\ 17 ATLW2AHELPER((LPSTR) alloca(_convert), _lpw, _convert))) 18 19 LPSTR AFXAPI AfxW2AHelper(LPSTR lpa, LPCWSTR lpw, int nChars) 20 { 21 if (lpw == NULL) 22 return NULL; 23 ASSERT(lpa != NULL); 24 // verify that no illegal character present 25 // since lpa was allocated based on the size of lpw 26 // don''t worry about the number of chars 27 lpa[0] = ''\0''; 28 VERIFY(WideCharToMultiByte(CP_ACP, 0, lpw, -1, lpa, nChars, NULL, NULL)); 29 return lpa; 30 } 31 32 LPWSTR AFXAPI AfxA2WHelper(LPWSTR lpw, LPCSTR lpa, int nChars) 33 { 34 if (lpa == NULL) 35 return NULL; 36 ASSERT(lpw != NULL); 37 // verify that no illegal character present 38 // since lpw was allocated based on the size of lpa 39 // don''t worry about the number of chars 40 lpw[0] = ''\0''; 41 VERIFY(MultiByteToWideChar(CP_ACP, 0, lpa, -1, lpw, nChars)); 42 return lpw; 43 }
3 .CString 对转化的支持
1 //m_cstrCaption是一个CString 对象。 2 3 BSTR bstrCaption =m_cstrCaption.AllocSysString(); 4 FireChange(&bstrCaption,&m_lAlignment); 5 ::SysFreeString(bstrCaption);
posted on 2012-04-20 15:16 Joshua Leung 阅读(509) 评论(0) 编辑 收藏 举报