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

时间:2011-11-08 00:18:22

标签: c++ winapi

其他信息 我正在构建一个使用WinHttpOpenRequest Api的应用程序,它需要LPCWSTR作为对象名称 我正在使用visual studio 2008

2 个答案:

答案 0 :(得分:12)

最简单的方法是使用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)分配的任何内存。

答案 1 :(得分:4)

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;

但就像提到的十福一样。如果可能,请使用generic text mapping