如何在 vc++ 中将 char* 转换为 LPWSTR..........................? [复制]

Posted

技术标签:

【中文标题】如何在 vc++ 中将 char* 转换为 LPWSTR..........................? [复制]【英文标题】:How to convert char* to LPWSTR in vc++..........................? [duplicate] 【发布时间】:2019-12-06 12:26:16 【问题描述】:

将 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);

【问题讨论】:

How to convert char* to wchar_t*?的可能重复 由于这是标记为mfc,因此解决方案实际上甚至不是单行:CStringW(a).GetString()。安全地使用它需要了解对象的生命周期。 【参考方案1】:

你的实现要么导致内存泄漏,要么让调用者响应释放由你的函数分配的内存,这总是一个非常错误和糟糕的模式。你应该像 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;

【讨论】:

以上是关于如何在 vc++ 中将 char* 转换为 LPWSTR..........................? [复制]的主要内容,如果未能解决你的问题,请参考以下文章

在 vc++ 中将字符串转换为双精度

如何在 vc 6.0 中将对象转换或分配为 Variant 类型

如何在 mFC VC++ 中将编辑控件的背景转换为透明?

在 VC++ 中将 TCHAR 转换为 LPWSTR?

如何在 C++ 中将字符串转换为 char 数组?

如何在C中将char转换为整数? [复制]