C ++에서 std :: 문자열을 lpcwstr로 변환하는 방법 (유니 코드)

StackOverflow https://stackoverflow.com/questions/27220

  •  09-06-2019
  •  | 
  •  

문제

std :: 문자열을 lpcwstr로 변환하기위한 메소드 또는 코드 스 니펫을 찾고 있습니다.

도움이 되었습니까?

해결책

MSDN 기사 링크에 감사드립니다. 이것이 바로 내가 찾고 있던 것입니다.

std::wstring s2ws(const std::string& s)
{
    int len;
    int slength = (int)s.length() + 1;
    len = MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, 0, 0); 
    wchar_t* buf = new wchar_t[len];
    MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, buf, len);
    std::wstring r(buf);
    delete[] buf;
    return r;
}

std::wstring stemp = s2ws(myString);
LPCWSTR result = stemp.c_str();

다른 팁

솔루션은 실제로 다른 제안보다 훨씬 쉽습니다.

std::wstring stemp = std::wstring(s.begin(), s.end());
LPCWSTR sw = stemp.c_str();

무엇보다도, 그것은 플랫폼 독립적입니다. h2h :)

ATL/MFC 환경에있는 경우 ATL 변환 매크로를 사용할 수 있습니다.

#include <atlbase.h>
#include <atlconv.h>

. . .

string myStr("My string");
CA2W unicodeStr(myStr);

그런 다음 Unicodest를 LPCWSTR로 사용할 수 있습니다. 유니 코드 문자열의 메모리는 스택에 생성되고 릴리스 된 다음 Unicodest의 소멸자가 실행됩니다.

std :: 문자열을 사용하는 대신 std :: wstring을 사용할 수 있습니다.

편집 : 죄송합니다. 더 이상 설명은 아니지만 실행해야합니다.

std :: wstring :: c_str () 사용

lpcwstr lpcwname = std :: wstring (strname.begin (), strname.end ()). c_str ()

string  myMessage="helloworld";
int len;
int slength = (int)myMessage.length() + 1;
len = MultiByteToWideChar(CP_ACP, 0, myMessage.c_str(), slength, 0, 0); 
wchar_t* buf = new wchar_t[len];
MultiByteToWideChar(CP_ACP, 0, myMessage.c_str(), slength, buf, len);
std::wstring r(buf);
 std::wstring stemp = r.C_str();
LPCWSTR result = stemp.c_str();
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top