Michael
Michael

Reputation: 6170

How to convert argv to wide chars in Win32 command line application?

I'm using the win32 api for C in my program to read from a serial port, it seems to be pretty low level stuff. Assuming that there is no better way of reading from a serial port, the CreateFile function involves a LPCWSTR argument, I've read and it looks like LPCWSTR is a wchar_t type. Firstly, I don't really understand the difference between wchar and char, I've read stuff about ansi and unicode, but I don't really know how it applies to my situation.

My program uses a main function, not wmain, and needs to get an argument from the command line and store it in a wchar_t variable. Now I know I could do this if I just made the string up on the spot;

wchar_t variable[1024];
swprintf(variable,1024,L"%s",L"randomstringETC");

Because it looks like the L converts char arrays to wchar arrays. However it does not work when I do;

wchar_t variable[1024];
swprintf(variable,1024,L"%s",Largv[1]);

obviously because it's a syntax error. I guess my question is, is there an easy way to convert normal strings to wchar_t strings?

Or is there a way to avoid this Unicode stuff completely and read from serial another way using C on windows..

Upvotes: 5

Views: 2189

Answers (3)

myforwik
myforwik

Reputation: 34

The L thing is only for string literals.

You need to convert argv string (presumably unsigned char) to wchar by using something like the winapi mbstowcs() function.

Upvotes: 1

Hans Passant
Hans Passant

Reputation: 942438

There is no winapi function named CreateFile. There's CreateFileW and CreateFileA. CreateFile is a macro that maps to one of these real function depending on whether the _UNICODE macro is defined. CreateFileW takes an LPCWSTR (aka const wchar_t*), CreateFileA takes an LPCSTR (aka const char*).

If you are not ready yet to move to Unicode then simply use the CreateFileA() function explicitly. Or change the project setting: Project + Properties, General, Character Set. There's a non-zero cost, the underlying operating system is entirely Unicode based. So CreateFileA() goes through a translation layer that turns the const char* into a const wchar_t* according to the current system code page.

Upvotes: 4

Mike Kwan
Mike Kwan

Reputation: 24477

MultiByteToWideChar can be used to map from ANSI to UNICODE. To do your swprintf call, you need to define an array of wchar like this:

WCHAR lala[256] = {0};
swprintf(lala, _countof(lala), L"%s", Largv[1]);

It is possible to avoid unicode by compiling your application against a multibyte character set but it's bad practice to do this unless you're doing so for legacy reasons. Windows will need to convert it back to unicode at some point eventually anyway because that is the encoding of the underlying OS.

Upvotes: 1

Related Questions