1

I am currently doing DirectX11 and trying to convert a UTF8 string into a LPCWSTR. I've written a utility function to aid me in the conversion:

// Convert an UTF8 string to a wide Unicode String
std::wstring WidenString(const std::string &string)
{
    int size_needed = MultiByteToWideChar(CP_UTF8, 0, string.c_str(), string.size(), NULL, 0);
    std::wstring wstring(size_needed, 0);
    MultiByteToWideChar(CP_UTF8, 0, string.c_str(), string.size(), &wstring[0], size_needed);
    return wstring;
}

I've used the debugger to verify if it works. This is working:

Debugger says wndClassEx.lpszClassName = L"Hello"

std::wstring str = WidenString("Hello");
wndClassEx.lpszClassName = str.c_str();

This is not working:

Debugger says wndClassEx.lpszClassName = L"ﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮ..."

wndClassEx.lpszClassName = WidenString("Hello").c_str();

Can someone explain to me what is wrong with my code?

Terence Lam
  • 223
  • 4
  • 15

1 Answers1

3

WidenString() returns a wstring by value. In the first snippet, wndClassEx.lpszClassName will point to a valid memory location as long as the variable str remains in scope i.e. it does not get destroyed.

In the second case the return value does go out of scope at the end of the expression (at the ;) and wndClassEx.lpszClassName then points to invalid memory.

Praetorian
  • 106,671
  • 19
  • 240
  • 328
  • 2
    @TerenceLam It's difficult to say how exactly to solve the problem without more context of where the code is being used. If you're passing the `WNDCLASSEX` structure to something like `RegisterClassEx` immediately, then the first version you've posted is the way to solve it. In the general case, the lifetime of the return value from `WidenString` must be at least as long as that of the `WNDCLASSEX` struct instance. – Praetorian Dec 29 '13 at 22:20