简体   繁体   English

如何将 LPCWSTR 转换为 wchar_t*?

[英]How convert LPCWSTR to wchar_t*?

I require to convert a LPCWSTR data to wchar_t* .我需要将LPCWSTR数据转换为wchar_t* I tried a bunch of methods, and some work, but when I try to get their code page, they are showing different values.我尝试了很多方法和一些工作,但是当我尝试获取它们的代码页时,它们显示了不同的值。

Code overview:代码概述:

std::string ChineseCharacter(LPCWSTR Data) //Data value: "丂\n"
{
    CString sHexValue = "";
    std::wstring sData(Data);

    wchar_t* str1 = (wchar_t*)Data;
    //wchar_t* str2 = (wchar_t*)_wcsdup(sData.c_str());

    wchar_t* str3 = (wchar_t*)(L"丂\n"); //u4E02 -- CP 8140 ** CP is needed

    for (int i = 0; i < 4; i++)
    {
        sHexValue2.Format("%02x", str1[i]);//-- 4E02 -- FAIL
        //sHexValue2.Format("%02x", str2[i]);//-- 4E02 -- FAIL
        sHexValue2.Format("%02x", str3[i]);//-- First loop: 81, second one: 40 -- OK
    }
}

According to the watcher, the values are:根据观察者的说法,这些值是:

str1= L"丂\n"
str3= L"@\n"

My doubt is, how can I pass the value of Data to a wchar_t* , equal as when I hard-code the value?我的疑问是,如何将Data的值传递给wchar_t* ,就像我对值进行硬编码时一样?

Reference:参考:
https://uic.io/en/charset/show/gb18030/ https://uic.io/en/charset/show/gb18030/

LPCWSTR is just an alias for const wchar_t* . LPCWSTR只是const wchar_t*的别名。 To convert that to wchar_t* , you can use const_cast , eg:要将其转换为wchar_t* ,您可以使用const_cast ,例如:

wchar_t* str = const_cast<wchar_t*>(Data);

(just make sure you don't write anything to the memory that is pointed at). (只需确保您没有向指向的 memory 写入任何内容)。

However, nothing in the code you have shown requires the use of non-const wchar_t* (or std::wstring , either), so you can simply loop through Data directly, there is no need to convert LPCWSTR to wchar_t* at all, eg:但是,您显示的代码中没有任何内容需要使用非常量wchar_t* (或std::wstring ),因此您可以直接循环Data ,根本不需要将LPCWSTR转换为wchar_t* ,例如:

std::string ChineseCharacter(LPCWSTR Data)
{
    CString sHexValue;

    for (int i = 0; (i < 4) && (Data[i] != L'\0'); ++i)
    {
        sHexValue.Format("%02hx", static_cast<unsigned short>(Data[i]));
    }

    return static_cast<char*>(sHexValue);
}

Alternatively, using just standard C++:或者,仅使用标准 C++:

std::string ChineseCharacter(const wchar_t *Data)
{
    std::ostringstream sHexValue;

    for (int i = 0; (i < 4) && (Data[i] != L'\0'); ++i)
    {
        sHexValue << std::setw(2) << std::setfill('0') << std::hex << static_cast<unsigned short>(Data[i]);
    }

    return sHexValue.str();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM