-1

how to copy to a character array from variant in c++. So far I have been able to come up with the snippet below. but need help in making it work.

_variant_t vt_Data(parent->CharData);

if(vt_Data.vt != VT_NULL)
{
   long ubound;
   long lbound;
   long length;
   TSTHR(SafeArrayGetLBound(vt_Data.parray, 1, &lbound));
   TSTHR(SafeArrayGetUBound(vt_Data.parray, 1, &ubound));
   if(length = ubound - lbound +1)
   {
      char *char_data = new char[length];

      TSTHR(SafeArrayAccessData(vt_Data.parray, (void **) &char_data))
      memcpy(char_data, vt_Data.parray, length);
      TSTHR(SafeArrayUnaccessData(vt_Data.parray));
   }
}
Indy9000
  • 8,651
  • 2
  • 32
  • 37
TrustyCoder
  • 4,749
  • 10
  • 66
  • 119
  • 1
    please edit your code so it displays properly – Indy9000 Jun 27 '12 at 17:03
  • 2
    Do you realize that the expression `if(length = ubound - lbound +1)` *assigns* `ubound - lbound +1` to `length` and then checks if `length` is non zero? If not, use `==` to check for equality, `=` is the assignment operator. – Ed S. Jun 27 '12 at 17:08
  • 2
    yes copy only when is length is not zero makes sense. – TrustyCoder Jun 27 '12 at 17:11
  • 1
    I think his point is the length will almost always be non-zero due to `+1` for the null. This check will also pass `lbound > ubound` and potentially allow allocation of negative length if that's a concern. – AJG85 Jun 27 '12 at 17:20

1 Answers1

0

If the type of parent->CharData is char*, bstr, or TCHAR* (or similar) then the following should work. (although untested)

//uses the bstr_t const assignment operator to extract the string
_bstr_t bstr = vt_Data; 

This will create a new copy of the string.

Tra5is
  • 146
  • 1
  • 7