7

I have a non-unicode (MBCS) C++ project building with VS2013.

Given a BSTR value, how should I pass this to printf safely?

Mr. Boy
  • 60,845
  • 93
  • 320
  • 589
  • Did you search? [This](http://stackoverflow.com/questions/13725519/how-to-convert-bstr-to-stdstring-in-visual-studio-c-2010) will get you most of the way there... – trojanfoe Sep 09 '15 at 14:39
  • 2
    Possible duplicate of [Convert BSTR to char\*](http://stackoverflow.com/questions/3648848/convert-bstr-to-char). – Frédéric Hamidi Sep 09 '15 at 14:40
  • 1
    Not a duplicate. `printf` can print `wchar_t` so there's no point in the conversion. – MSalters Sep 09 '15 at 14:42
  • Just use the %ls format specifier. – Hans Passant Sep 09 '15 at 14:43
  • I did search and found no direct duplicate, or direct answer on other sites - which I found very surprising. I wondered if `_bstr_t` is the answer, as it so often is with BSTR? – Mr. Boy Sep 09 '15 at 14:43

2 Answers2

10

A BSTR really is a WCHAR* with preceding length information. You can ignore that length part for printing purposes. So:

BSTR str = foo();
printf("%S", str); // Capital S
MSalters
  • 173,980
  • 10
  • 155
  • 350
1

A BSTR is a pointer to a length-prefixed (at offset -4) and 0-terminated wide-character string. You can pass it to any function that is capable of handling a 0-terminated wide-character string. (The actual string starts at offset 0.)

If the target function cannot handle wide characters, then you need to convert the string to multibyte characters (this is the case if you want to use standard printf where the S type field character is not available). This (already commented) link provides information about that: Convert BSTR to char*

@MSalters' answer has the code example (don't want to duplicate 2 trivial lines): https://stackoverflow.com/a/32482688/682404

Community
  • 1
  • 1
xxbbcc
  • 16,930
  • 5
  • 50
  • 83