_bstr_t to char*, amazing result
Asked Answered
P

1

5

first:

LPCTSTR asdfsdf = (LPCTSTR)(_bstr_t)v;
printf("%s\n", asdfsdf);

second:

printf("%s\n", (LPCTSTR)(_bstr_t)v);

they are the same, but the first condition causes unreadable code

why?

Petulancy answered 6/12, 2012 at 7:52 Comment(0)
P
9

The _bstr_t class encapsulates a BSTR inside a C++ class. In your first instance:

LPCTSTR asdfsdf = (LPCTSTR)(_bstr_t)v;

you are creating a _bstr_t object, extracting the LPCTSTR out of it, but then the temporary _bstr_t object gets destructed. Whatever asdfsdf pointed to is now deallocated and can no longer be used.

In your second example

printf("%s\n", (LPCTSTR)(_bstr_t)v);

the temporary _bstr_t object is not destructed until after the printf() is called, so there is no problem using the LPCTSTR value.

Pocked answered 6/12, 2012 at 7:57 Comment(2)
thanks, but i still have problem. the variable 'v' above is declared as this: _variant_t v = ret->GetCollect((long)1); as you said, _bstr_t object doesn't exist, but variable 'v' still exist. why this can't work?Petulancy
It doesn't matter what v is. The problem is that the _bstr_t temporary object creates a copy of the data from v when it is constructed, and deallocates that copy when the temporary is destructed.Pocked

© 2022 - 2024 — McMap. All rights reserved.