views:

48

answers:

2

How to convert a char[256] to wstring?

update. here is my current code:

char testDest[256];
char *p= _com_util::ConvertBSTRToString(url->bstrVal);

for (int i = 0; i <= strlen(p); i++)
{
  testDest[i] = p[i];   
}

// need to convert testDest to wstring to I can pass it to this below function...

writeToFile(testDestwstring);
+3  A: 

MultiByteToWideChar will return a UTF-16 string. You need to specify the source codepage.

renick
Oh, I had somehow missed the `visual-c++` tag. On Windows, this is the way to go. `+1` from me.
sbi
+1, but beware of null BSTRs - they correspond to empty strings and can crash an unaware program.
sharptooth
+2  A: 

If your input is BSTR (as it seems to be) the data is already Unicode and you can just cast this directly to wstring as follows. _bstr_t has implicit conversions to both char* and wchar* which avoid the need for manual Win32 code conversion.

if (url->bstrVal)
{
    // true => make a new copy - can avoid this if source 
    // no longer needed, by using false here and avoiding SysFreeString on source

    const _bstr_t wrapper(url->bstrVal, true); 
    std::wstring wstrVal((const _wchar_t*)wrapper);
}

See here for more details on this area of Windows usage. It's easy to mess up the use of the Win32 API in this area - using the BSTR wrapper to do this avoids both data copy (if used judiciously) and code complexity.

Steve Townsend
This is the better answer - the conversion through `char[]` is **not** lossless.
MSalters
Will wstring take care of null BSTR?
sharptooth
My experience is that passing NULL to `string` causes access violation and I would expect the same with `wstring`. I would check this before constructing _bstr_t and handle appropriately. Edited code to show this guard.
Steve Townsend
Okay, +1 now...
sharptooth
@Steve: In fact, the standard explicitly said that passing `MULL` to the `std::string` constructor taking a `const char*` is invoking _UB_.
sbi