Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass BSTR to printf?

Tags:

c++

printf

bstr

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

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

like image 882
Mr. Boy Avatar asked Sep 09 '15 14:09

Mr. Boy


2 Answers

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
like image 118
MSalters Avatar answered Nov 19 '22 05:11

MSalters


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

like image 21
xxbbcc Avatar answered Nov 19 '22 04:11

xxbbcc