C++ 如何在c++中从LPCSTR转换为LPCWSTR

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8044506/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 17:54:53  来源:igfitidea点击:

how to convert from LPCSTR to LPCWSTR in c++

c++winapi

提问by andrewmag

additional info im building an application which use the WinHttpOpenRequest Api which requires LPCWSTR for the object name and im using visual studio 2008

附加信息我正在构建一个使用 WinHttpOpenRequest Api 的应用程序,该应用程序需要 LPCWSTR 作为对象名称,我正在使用 Visual Studio 2008

回答by Ferruccio

The simplest way is to use ATL:

最简单的方法是使用 ATL:

#include <Windows.h>
#include <atlbase.h>
#include <iostream>

int main(int argc, char *argv[]) {
    USES_CONVERSION;
    LPCSTR a = "hello";
    LPCWSTR w = A2W(a);
    std::wcout << w << std::endl;
    return 0;
}

Any memory allocated by A2W (ANSI to Wide) will be freed when the function exits.

当函数退出时,任何由 A2W(ANSI 到 Wide)分配的内存都将被释放。

回答by parapura rajkumar

Converting from char *has a nice sample

从 char * 转换有一个很好的示例

char *orig = "Hello, World!";
cout << orig << " (char *)" << endl;

// Convert to a wchar_t*
size_t origsize = strlen(orig) + 1;
const size_t newsize = 100;
size_t convertedChars = 0;
wchar_t wcstring[newsize];
mbstowcs_s(&convertedChars, wcstring, origsize, orig, _TRUNCATE);
wcscat_s(wcstring, L" (wchar_t *)");
wcout << wcstring << endl;

But like tenfour mentioned. Use generic text mappingif possible

但是就像tenfour提到的那样。如果可能,使用通用文本映射