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

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!
1 Solution
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;
that '_bstr_t()' already provides.
KanivorousAuthor 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):

    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

Open in new window

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.

Join & Write a Comment

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now