【问题标题】:how to convert from LPCSTR to LPCWSTR in c++如何在 C++ 中将 LPCSTR 转换为 LPCWSTR
【发布时间】:2011-12-24 01:49:48
【问题描述】:

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

【问题讨论】:

标签: c++ winapi


【解决方案1】:

最简单的方法是使用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;
}

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

【讨论】:

  • 那些 ATL 3.0 宏已在十多年前被版本 7.0 ATL and MFC String Conversion Macros 取代。其中,ATL 7.0 宏不再需要使用USES_CONVERSION 宏。另外,您可以使用 const-correct 变体,例如在您的示例中:CA2W(a).
  • 然而,在目前的 2021 年,似乎没有 ATL 库了。还有其他想法吗?
  • @IneoSenigupta - 我已经很长时间没有积极参与 Windows/C++ 工作了,但是据我所知,ATL 在 VS2019 中。见docs.microsoft.com/en-us/cpp/atl/…
【解决方案2】:

Converting from 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;

但就像提到的 tenfour 一样。尽可能使用generic text mapping

【讨论】:

    猜你喜欢
    • 2021-12-17
    • 2013-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-26
    • 2011-07-23
    • 2010-11-15
    相关资源
    最近更新 更多