为了方便处理VARIANT类型的变量,Windows还提供了这样一些非常有用的函数:
VariantInit —— 将变量初始化为VT_EMPTY;
VariantClear —— 消除并初始化VARIANT;
VariantChangeType —— 改变VARIANT的类型;
VariantCopy —— 释放与目标VARIANT相连的内存并复制源VARIANT。
COleVariant类是对VARIANT结构的封装。它的构造函数具有极为强大大的功能,当对象构造时首先调用VariantInit进行初始化,然后根据参数中的标准类型调用相应的构造函数,并使用VariantCopy进行转换赋值操作,当VARIANT对象不在有效范围时,它的析构函数就会被自动调用,由于析构函数调用了VariantClear,因而相应的内存就会被自动清除。除此之外,COleVariant的赋值操作符在与 VARIANT类型转换中为我们提供极大的方便。例如下面的代码:
| COleVariant v1("This is a test"); // 直接构造 COleVariant v2 = "This is a test"; // 结果是VT_BSTR类型,值为"This is a test" COleVariant v3((long)2002); COleVariant v4 = (long)2002; // 结果是VT_I4类型,值为2002 |
_variant_t是一个用于COM的VARIANT类,它的功能与COleVariant相似。不过在Visual C++.NET的MFC应用程序中使用时需要在代码文件前面添加下列两句:
#include "comutil.h"
#pragma comment( lib, "comsupp.lib" )
四、CComBSTR和_bstr_t
CComBSTR是对BSTR数据类型封装的一个ATL类,它的操作比较方便。例如:
| CComBSTR bstr1; bstr1 = "Bye"; // 直接赋值 OLECHAR* str = OLESTR("ta ta"); // 长度为5的宽字符 CComBSTR bstr2(wcslen(str)); // 定义长度为5 wcscpy(bstr2.m_str, str); // 将宽字符串复制到BSTR中 CComBSTR bstr3(5, OLESTR("Hello World")); CComBSTR bstr4(5, "Hello World"); CComBSTR bstr5(OLESTR("Hey there")); CComBSTR bstr6("Hey there"); CComBSTR bstr7(bstr6); // 构造时复制,内容为"Hey there" |
_bstr_t是是C++对BSTR的封装,它的构造和析构函数分别调用SysAllocString和SysFreeString函数,其他操作是借用BSTR API函数。与_variant_t相似,使用时也要添加comutil.h和comsupp.lib。
五、BSTR、char*和CString转换
(1) char*转换成CString
若将char*转换成CString,除了直接赋值外,还可使用CString::Format进行。例如:
| char chArray[] = "This is a test"; char * p = "This is a test"; |
或
| LPSTR p = "This is a test"; |
或在已定义Unicode应的用程序中
| TCHAR * p = _T("This is a test"); |
或
| LPTSTR p = _T("This is a test"); CString theString = chArray; theString.Format(_T("%s"), chArray); theString = p; |
(2) CString转换成char*
若将CString类转换成char*(LPSTR)类型,常常使用下列三种方法:
方法一,使用强制转换。例如:
| CString theString( "This is a test" ); LPTSTR lpsz =(LPTSTR)(LPCTSTR)theString; |
方法二,使用strcpy。例如:
| CString theString( "This is a test" ); LPTSTR lpsz = new TCHAR[theString.GetLength()+1]; _tcscpy(lpsz, theString); |
需要说明的是,strcpy(或可移值Unicode/MBCS的_tcscpy)的第二个参数是 const wchar_t* (Unicode)或const char* (ANSI),系统编译器将会自动对其进行转换。

