Visual c++ 如何在vc++中将char*转换为LPWSTR。。。。。。。。。。。。。。。。。。。。。。。。。。?

Visual c++ 如何在vc++中将char*转换为LPWSTR。。。。。。。。。。。。。。。。。。。。。。。。。。?,visual-c++,mfc,Visual C++,Mfc,这是将char*转换为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); } 您的实现要么会导致内存泄漏,要

这是将char*转换为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);
}

您的实现要么会导致内存泄漏,要么会使调用方响应释放由您的函数分配的内存,这通常是一种非常错误和糟糕的模式。您最好像std::wstring那样返回一个关心自身内存的对象:

    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;
}
可能的重复因为它被标记了,所以解决方案实际上甚至不是一行:CStringWa.GetString。安全地使用它需要了解对象的生命周期。