How to convert char* to LPCWSTR?

前端 未结 2 1699
醉话见心
醉话见心 2020-11-29 10:46

I know this has already been discussed in several questions on SO, but none of those solutions have worked for me.

I start with a char* because this is

相关标签:
2条回答
  • 2020-11-29 11:06

    Following Hans Passant's advice regarding pointers to local variables, I worked out this approach, which seems to work well:

    wchar_t *convertCharArrayToLPCWSTR(const char* charArray)
    {
        wchar_t* wString=new wchar_t[4096];
        MultiByteToWideChar(CP_ACP, 0, charArray, -1, wString, 4096);
        return wString;
    }
    

    I'm aware that the use of new requires memory management, which I perform in the function that calls this one.

    0 讨论(0)
  • 2020-11-29 11:07

    Since cs is a const char*, cs[1] is a const char. C++ won't convert it to a pointer for you, because in most cases that doesn't make sense.

    You could instead say &cs[1] or cs+1 if the intent is to skip the first char. (That's what you're doing when you pass a pointer to the 1th element; in C++, indexes start at 0.) If the intent is to pass the whole string, then just pass cs.

    0 讨论(0)
提交回复
热议问题