USES_CONVERSION; char buffer[20]; HRESULT hr= S_OK; // Create SafeArray of VARIANT BSTRs SAFEARRAY *pSA; SAFEARRAYBOUND aDim[1]; aDim[0].lLbound=0; aDim[0].cElements=10; pSA= SafeArrayCreate(VT_VARIANT,1,aDim); if (pSA != NULL) ...{ _variant_t vOut; for (long l= aDim[0].lLbound; l< (aDim[0].cElements + aDim[0].lLbound); l++) ...{ ltoa(l,buffer,10); vOut= A2W(buffer); // assignment operator automates memory allocation for BSTR if (hr= SafeArrayPutElement(pSA, &l, &vOut)) ...{ SafeArrayDestroy(pSA); // does a deep destroy on error return hr; } } } // clean up here only if you do not return SafeArray as an [out, retval] SafeArrayDestroy(pSA); // again does a deep destroy
_variant_t& operator=(constwchar_t* pSrc) throw(_com_error); // Assign a VT_BSTR
为了使用_variant_t类,你必须在头文件中加入#include<comdef.h>。我在简化的版本中消除了the array of longs,在我阅读了Shelley Powers "Developing ASP Components Second Edition",构建了下面的代码:
USES_CONVERSION; // enables use of ATL conversion macro A2W char buffer[20]; // used to store ANSI string HRESULT hr= S_OK; // Create SafeArray of VARIANT BSTRs SAFEARRAY *pSA; SAFEARRAYBOUND aDim[1]; // a one dimensional array aDim[0].lLbound=0; // Visual Basic arrays start with index 0 aDim[0].cElements=10; pSA= SafeArrayCreate(VT_VARIANT,1,aDim); // create a 1D SafeArray of VARIANTS if (pSA != NULL) ...{ long aLong[1]; // iterate over array adding VARIANTs of type VT_BSTR for (long l= aDim[0].lLbound; l< (aDim[0].cElements + aDim[0].lLbound); l++) ...{ VARIANT vOut; VariantInit(&vOut); vOut.vt= VT_BSTR; // set type ltoa(l,buffer,10); // convert long to ANSI string value vOut.bstrVal= ::SysAllocString(A2W(buffer)); // system wide "new" aLong[0]= l; // set index value if (hr= SafeArrayPutElement(pSA, aLong, &vOut)) ...{ // "correctly" copies VARIANT VariantClear(&vOut); // release BSTR from memory on error SafeArrayDestroy(pSA); // does a deep destroy on error return hr; } VariantClear(&vOut); // does a deep destroy of source VARIANT }// end iteration } // clean up here only if you do not return SafeArray as an [out, retval] SafeArrayDestroy(pSA); // again does a deep destroy