Link to home
Start Free TrialLog in
Avatar of meverest
meverestFlag for Australia

asked on

casting from BSTR <-> char *

Hi folks,

am i allowed to do:

char *str1 = strdup("hello");
BSTR str2 = (BSTR) str1;

or vice-versa?

what happens if i do this, and if it is not legal, how can i convert from wchar to char?

thanks and regards.
ASKER CERTIFIED SOLUTION
Avatar of nietod
nietod

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of nietod
nietod

>> how can i convert from wchar to char?
use WideCharToMultiByte().
If you're using MFC (actually I think this works in non-MFC apps as well), you can also use the string-type conversion macros in afxpriv.h.

For instance, to convert from WCHAR to CHAR, you can use the W2T macro.

There is a whole family of these that convert from almost any string type to almost any other.  (I say "almost" since there is probably some type that is not supported.)
The macros that jhance mentioned are actually from ATL. See

TN059: Using MFC MBCS/Unicode Conversion Macros
http://msdn.microsoft.com/isapi/msdnlib.idc?theURL=/library/devprods/vs6/visualc/vcmfc/_mfcnotes_tn059.htm

String Conversion Macros
http://msdn.microsoft.com/isapi/msdnlib.idc?theURL=/library/devprods/vs6/visualc/vcmfc/_atl_string_conversion_macros.htm

If you are using Visual C++ 5.0 or above, you may also use the _bstr_t class since it has the operator wchar_t*, char*.

_bstr_t
http://msdn.microsoft.com/isapi/msdnlib.idc?theURL=/library/devprods/vs6/visualc/vclang/_pluslang__bstr_t.htm
nietod> To convert a C-stly string to a BSTR you use the
 nietod> SysAllocString() function defined in oleauto.h.  Like

 nietod> BSTR str2 = SysAllocString("hello");

Your code doesn't compile.  I think you meant to show

  BSTR str2 = SysAllocString(L"hello");

..B ekiM
Thanks--everyone.
Avatar of meverest

ASKER

thanks netiod,

although i am already using SysAllocString() (and SysReAllocString()), i found what i was after when lloking into WideCharToMultiByte and related functions.

regards.