0

Is it the correct way of converting char* to LPWSTR ?

void convertcharpointerToLPWSTR(char *a) { int nSize = MultiByteToWideChar(CP_ACP, 0, a, -1, NULL, 0); LPWSTR a_LPWSTR = new WCHAR[nSize]; MultiByteToWideChar(CP_ACP, 0, a, -1, a_LPWSTR, nSize); } 
2
  • 1
    Possible duplicate of How to convert char* to wchar_t*? Commented Dec 6, 2019 at 12:29
  • Since this is tagged mfc, the solution is really not even a one-liner: CStringW(a).GetString(). Using this safely requires understanding of object life times. Commented Dec 7, 2019 at 13:50

1 Answer 1

1

Your implementation would either cause a memory leak or making the caller responsive for freeing the memory which was allocated by your function, which is always a really faulty and bad pattern. You should better return an object caring for its own memory as std::wstring does:

 inline std::wstring a2w(LPCSTR psz, UINT codepage) { if (!psz || *psz == 0) return std::wstring(); int nLen = int(strlen(psz)); int resultChars = ::MultiByteToWideChar(codepage, 0, psz, nLen, nullptr, 0); std::wstring result(resultChars, (wchar_t)0); ::MultiByteToWideChar(codepage, 0, psz, nLen, &result[0], resultChars); return result; } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.