Praveen Katiyar' Blog

Learning along the way . . . .

Packing a array inside a VARIANT (VC++ 6.0) (Series 2 of N)

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 )

    //Initialize the VARIANT (Type is SAFEARRAY of BSTRs)
    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

    //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.

  1. Allocating the desired temporary buffer space to hold the array of bytes, and filling that array with values one need to return.
  2. creating a safe array of the desired (VT_BSTR) type.
  3. copying the temporary buffer to the safe array of the variant.
  4. 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)) ; 

    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
    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.


July 18, 2013 - Posted by | CodeProject, MFC, Win32 | , ,

No comments yet.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: