andrewmag
andrewmag

Reputation: 262

how to convert from LPCSTR to LPCWSTR in c++

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

Upvotes: 11

Views: 30165

Answers (2)

Ferruccio
Ferruccio

Reputation: 100728

The simplest way is to use 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.

Upvotes: 14

parapura rajkumar
parapura rajkumar

Reputation: 24413

Converting from char * has a nice sample

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 mapping if possible

Upvotes: 4

Related Questions