• Status: Solved
• Priority: Medium
• Security: Public
• Views: 6088

# Convert VARIANT to string array

There's a lot of answers lying around for visual basic and C# regarding this but I need one for C++.

Basically I am calling a function which passes by reference a VARIANT and an array of strings gets stored to this. Once I get this VARIANT stored in var, I call VariantInit(&var)... and I'm kind of stuck how to convert this to a simple std::string array. I want to read the strings that are stored in here. Thanks!
0
Kanivorous
1 Solution

Commented:
Could you be a bit more specific about the type of the VARIANT? If it is a VT_BSTR, you could just use a '_bstr_t' (http://msdn2.microsoft.com/en-us/library/zthfhkd6(VS.80).aspx, "_bstr_t Class") just like

#include <comdef.h>

//

VARIANT vt = GettingVariantFromSomewhere();

_bstr_t b (vt);

char* pStr = (char*) b;
wchar_t* pwStr = (wchar_t*) b;

That code uses the operators

operator const wchar_t*( ) const throw( );
operator wchar_t*( ) const throw( );
operator const char*( ) const;
operator char*( ) const;

0

Author Commented:
Okay I found out how to do it.. Basically I assumed VARIANT was an array of strings, not only a string like you mentioned. I'm still very new to VARIANTs so still trying to learn... Just as a reference, what I ended up doing was (very roughly):

VARIANT var;
VARIANT vtBstr;
VariantInit(&var);
VariantInit(&vtBstr);
myGetArrayOfStrings(&var);
if(var.vt==VT_EMPTY)
goto end;
long lCount = var.parray->rgsabound[0].cElements;
for(long i=0; i<lCount; i++)
{
SafeArrayGetElement(var.parray, &i, &vtBstr);
std::string sSomeString = _com_util::ConvertStringToBSTR(vtBstr.bstrVal);
// Do whatever with string
}

end:
VariantClear(&var);
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.