How to pass BSTR to printf?
Asked Answered
M

2

6

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

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

Mainland answered 9/9, 2015 at 14:36 Comment(5)
Did you search? This will get you most of the way there...Draconic
Possible duplicate of Convert BSTR to char*.Immune
Not a duplicate. printf can print wchar_t so there's no point in the conversion.Mccollough
Just use the %ls format specifier.Episode
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?Mainland
M
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
Mccollough answered 9/9, 2015 at 14:44 Comment(4)
Can you point out the documentation for the capital S printf specifier? It doesn't appear to be standard C.Improvisatory
@user2079303 msdn.microsoft.com/en-us/library/hf4y5e3w.aspx - this is MSDN so it is Microsoft-specific - the link says so.Mallet
I figured that with BSTR being Microsoft-specific this isn't an issue. %ls is portable.Mccollough
You can also use wprintf()Rhombus
M
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://mcmap.net/q/1666447/-how-to-pass-bstr-to-printf

Mallet answered 9/9, 2015 at 14:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.