Converting between VARIANT and std::string

  • Thread starter Thread starter Torben Laursen
  • Start date Start date
T

Torben Laursen

Hi

Can anyone show me how to convert between VARIANT and std::string and back,
thanks!

Torben
 
Torben said:
Hi

Can anyone show me how to convert between VARIANT and std::string and
back, thanks!

Here's one way, not necessarily the best. In general, std::string doesn't
play very well with VARIANT.

#include <comutil.h>
#include <string>

std::string from_variant(VARIANT& vt)
{
_bstr_t bs(vt);
return std::string(static_cast<const char*>(bs));
}

void to_variant(const std::string& str, VARIANT& vt)
{
_bstr_t bs(str.c_str());
reinterpret_cast<_variant_t&>(vt) = bs;
}

-cd
 
Hi Carl

Thanks.
I get a exception when I try to use: to_variant(const std::string& str,
VARIANT& vt),
it throw's at reinterpret_cast. Do you know whats wrong, thanks!

Torben
 
Torben said:
Hi Carl

Thanks.
I get a exception when I try to use: to_variant(const std::string&
str, VARIANT& vt),
it throw's at reinterpret_cast. Do you know whats wrong, thanks!

The following works correctly in my test:

// <Code>
#include <comutil.h>
#include <string>
#include <iostream>

std::string from_variant(VARIANT& vt)
{
_bstr_t bs(vt);
return std::string(static_cast<const char*>(bs));
}

void to_variant(const std::string& str, VARIANT& vt)
{
_bstr_t bs(str.c_str());
reinterpret_cast<_variant_t&>(vt) = bs;
}

int main()
{
std::string str("This is a test");
_variant_t vt;
to_variant(str,vt);
std::string str2 = from_variant(vt);
std::cout << "str: " << str << "\nstr2: " << str2 << "\n";
}

// </Code>


R:\>cl -GX -GR convert0817.cpp comsupp.lib
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 13.10.3077 for 80x86
Copyright (C) Microsoft Corporation 1984-2002. All rights reserved.

convert0817.cpp
Microsoft (R) Incremental Linker Version 7.10.3077
Copyright (C) Microsoft Corporation. All rights reserved.

/out:convert0817.exe
convert0817.obj
comsupp.lib

R:\>convert0817
str: This is a test
str2: This is a test
 
Torben said:
Hi Carl

Thanks.
I get a exception when I try to use: to_variant(const std::string&
str, VARIANT& vt),
it throw's at reinterpret_cast. Do you know whats wrong, thanks!

I believe that the _bstr_t(const variant_t&) constructor will throw an
exception if the variant contains a type that can't be converted to a
string. What's in the VARIANT that you're supplying?

-cd
 
Back
Top