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);
}
  • 1
    Possible duplicate of [How to convert char\* to wchar\_t\*?](https://stackoverflow.com/questions/8032080/how-to-convert-char-to-wchar-t) – GSerg Dec 06 '19 at 12:29
  • Since this is tagged [tag:mfc], the solution is really not even a one-liner: `CStringW(a).GetString()`. Using this safely requires understanding of object life times. – IInspectable Dec 07 '19 at 13:50

1 Answers1

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;
}
Nick
  • 472
  • 3
  • 18