كيفية تحويل std::string إلى LPCWSTR في C++ (Unicode)

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

  •  09-06-2019
  •  | 
  •  

سؤال

أنا أبحث عن طريقة أو مقتطف تعليمات برمجية لتحويل std::string إلى 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();

وأفضل ما في الأمر أنها منصة مستقلة.ح2س :)

إذا كنت في بيئة ATL/MFC، فيمكنك استخدام ماكرو تحويل ATL:

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

. . .

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

يمكنك بعد ذلك استخدام unicodeStr باعتباره LPCWSTR.يتم إنشاء ذاكرة سلسلة Unicode على المكدس ويتم تحريرها ثم يتم تنفيذ أداة التدمير لـ unicodeStr.

بدلاً من استخدام std::string، يمكنك استخدام 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