This is the second post about variant, in this post I I am going to explain, how an array of strings can be packed inside a VARIANT variable.
Packing a array of string inside a Variant
int PackVariantWithStringArray(short nCnt, VARIANT * pVar )
{
USES_CONVERSION ;
//Initialize the VARIANT (Type is SAFEARRAY of BSTRs)
VariantInit(pVar);
pVar->vt = VT_ARRAY | VT_BSTR;
// Define a safe array of nCnt Item and Starting index as 0
SAFEARRAYBOUND safeBounds = { nCnt, 0};
//Create the Safe Array passing it the bounds
SAFEARRAY* pSafeArray = SafeArrayCreate(VT_BSTR, 1, &safeBounds);
//Get a pointer, actually increments the array’s lock count)
BSTR* bstrArray = NULL;
SafeArrayAccessData(pSafeArray, (void**)&bstrArray);
for ( int i = 0 ; i < nCnt ; i++ )
{
CString strTmp ;
strTmp.Format ( _T("This is Item %2d"), i );
bstrArray [i] = strTmp.AllocSysString () ;
}
//done wth populating, Decrement the array’s lock count
SafeArrayUnaccessData(pSafeArray);
//Assign our VARIANT out param with the array
pVar->parray = pSafeArray ;
return nCnt ;
}
as it can be seen from the above code, it involves following steps.
- Allocating the desired temporary buffer space to hold the array of bytes, and filling that array with values one need to return.
- creating a safe array of the desired (VT_BSTR) type.
- copying the temporary buffer to the safe array of the variant.
- free the memory allocated for temporary buffer. (avoid memory leaks).
Fetching a array of strings from a variant.
TCHAR ** UnPackVariantWithStringArray(short nCnt, VARIANT var )
{
TCHAR **pBuffer = (TCHAR **) calloc ( nCnt, sizeof (INT)) ;
USES_CONVERSION ;
SAFEARRAY* pSafeArray = var.parray ;
//pointer to array data, actually increments the lock count
BSTR* bstrArray = NULL ;
SafeArrayAccessData ( pSafeArray, (void**)&bstrArray);
for ( int i = 0 ; i < nCnt ; i++ )
{
LPTSTR szTmp = OLE2T ( bstrArray [i] ) ;
int nLen = _tcslen ( szTmp );
pBuffer [i]= (TCHAR *) calloc ( nLen, sizeof ( TCHAR));
_tcscpy ( pBuffer [i], szTmp);
}
//Done wth populating, Decrement the array’s lock count
SafeArrayUnaccessData(pSafeArray);
return pBuffer ;
}
these conversion is useful in middleware scenario. in the next article I will explain how to pack array of structure inside a variant.