locked
How to convert variables from 'char *' to 'LPCWSTR'?

    Question

  • Hi,

    I use serial communication. I failed to use function 'CreateFile()'. The error information is:

    error C2664: 'CreateFileW' : cannot convert parameter 1 from 'char *' to 'LPCWSTR'

    The corresponding code is listed as following:
    char *szPort = new char[50];         //define variable
    sprintf(szPort, "COM%d", portnr);   //so szPort = COM1, if portnr = 1
    //compile error in the next line:
    m_hComm = CreateFile(szPort,                        // communication port string (COMX)
                             GENERIC_READ | GENERIC_WRITE,    // read/write types
                             0,                                // comm devices must be opened with exclusive access
                             NULL,                            // no security attributes
                             OPEN_EXISTING,                    // comm devices must use OPEN_EXISTING
                             FILE_FLAG_OVERLAPPED,            // Async I/O
                             0);

    Could you help me?
    Monday, April 16, 2007 5:13 PM

Answers

  •  farming wrote:


    error C2664: 'CreateFileW' : cannot convert parameter 1 from 'char *' to 'LPCWSTR'

    The corresponding code is listed as following:
    char *szPort = new char[50];         //define variable
    sprintf(szPort, "COM%d", portnr);   //so szPort = COM1, if portnr = 1
    //compile error in the next line:
    m_hComm = CreateFile(szPort,                        // communication port string (COMX)
                             [ ... other options ... ]
                             0);

    You have a couple of choices.

     

    1. An easy choice is to use CreateFileA.  You are defaulting to CreateFileW because Unicode is set as the default for VC++ projects.   (This was done to facilitate the transfer over to using Unicode.  Many API function names are now macros that default to one of two different implementation names.  I don't know if it was a good idea at the time, but it is a pain for VC++ 2005 EE enthusiasts and beginners who haven't experienced the evolution of the Windows API.) 

     

    2. Another choice is to go into your Project Properties and turn off the default Unicode setting.  (I'm a purist and I am likely to do both so that everything is explicit.)

     

    There are more elaborate things you can do, but I wouldn't recommend any of them until you have more experience with how the character-handling works in C/C++ and the Windows Platform SDK.

     

    You should generally look up these SDK functions in the on-line Help to find out when/whether there are automatic variations between Unicode and not Unicode and what name to use when you want to be very specific about the kind of character cells you are using. 

     

     - Dennis

    Monday, April 16, 2007 7:08 PM