0

I want to convert a vector string to BSTR and to V_BSTR but when i debug the output it shows some strange output. Below is the code which am trying.

vector<string> v = explode("*", Types);

VARIANT vHeads = { 0 };
BSTR Heads = SysAllocStringByteLen(v[0].c_str(), v[0].size());
V_VT( &vHeads ) = VT_BSTR;
V_BSTR( &vHeads ) = Heads;

char buff[1024];
sprintf_s(buff, "Vhead: %S And Head: %s", vHeads,Heads);
MessageBoxA(NULL, buff, "Debug", MB_OK | MB_ICONQUESTION);

The vhead output is some weird output but heads output is as expected. Can someone say what's wrong?

  • 1
    `%S` is not the right format specifier for `VARIANT`, and `%s` is not the right format specifier for `BSTR`. If you use the wrong format specifier you get undefined behaviour. – M.M Feb 17 '16 at 19:56
  • @M.M Please mention the right format specifier. – Toe.Pal Feb 17 '16 at 20:10
  • There is none for Variant, so far as I know. `%S` is the specifier for `wchar_t`. But since you used `SysAllocStringByteLen` I think you should write `sprintf_s(buff, "Head: %s", (char *)Heads);` . – M.M Feb 17 '16 at 20:13
  • The documentation says `SysAllocStringByteLen` creates a copy of the bytes, with no translation to Unicode. Then treating it as a Unicode string produces garbage. For modern Windows programming just use the basic wide string functions. – Cheers and hth. - Alf Feb 17 '16 at 20:18
  • @Cheersandhth.-Alf Can you show me more clue or example or how may i convert vector string to usable BSTR Value. – Toe.Pal Feb 17 '16 at 20:33
  • Depends on the encoding of the `string`. Assuming it's ANSI you can use http://stackoverflow.com/a/17066676/464581 Disclaimer: I haven't scrutinized the code. – Cheers and hth. - Alf Feb 17 '16 at 20:43
  • `SysAllocStringByteLen` is more intended to be used when transporting binary data via BSTRs – M.M Feb 17 '16 at 20:44
  • @M.M. No there is no automatic conversion `string` → `wstring`. – Cheers and hth. - Alf Feb 17 '16 at 20:44
  • So someone say me how would i transfer string to bstr actually then. – Toe.Pal Feb 17 '16 at 20:55
  • @Cheers and hth. - Alf error C2664: 'MultiByteToWideChar' : cannot convert parameter 3 from 'std::basic_string<_Elem,_Traits,_Ax>' to 'LPCSTR'. – Toe.Pal Feb 17 '16 at 20:58
  • @Toe.Pal: `LPCSTR` is Microsoft-speak for `char const*`. If you're using Visual Studio than you can probably just hover the mouse cursor over the word to get a definition. Or "peek definition". – Cheers and hth. - Alf Feb 17 '16 at 21:07
  • @Cheersandhth.-Alf Your link stackoverflow.com/a/17066676/464581 helped me. thanks. but by adding '.c_str()' to string datat type. – Toe.Pal Feb 17 '16 at 21:37

0 Answers0