title: Converting a string to LPCWSTR for CreateFile() to address a serial port
body: <p>I seem to be having a bit of a TEXT / UNICODE problem when using the windows CreateFile function for addressing a serial port.  Can someone please help point out my error?</p>
  
  <p>I'm writing a Win32 console application in VC++ using VS 2008.</p>
  
  <p>I can create a handle to address the serial port like this:</p>
  
  <pre><code>#include &lt;iostream&gt;    
  #include &lt;windows.h&gt;
  #include &lt;string&gt;
  
  int main()
  {
  
     HANDLE hSerial;
  
     hSerial = CreateFile( L"\\\\.\\COM20",
                           GENERIC_READ | GENERIC_WRITE,
                           0,
                           0,
                           OPEN_EXISTING,
                           FILE_ATTRIBUTE_NORMAL,
                           0);`
  
     return 0;
  }
  </code></pre>
  
  <p>That works just fine (the <code>\\\\.\\</code> bit is required for comports greater than COM9 and works for those up to COM9 also).  The problem is that my comport will not always be COM20, so I'd like to have the user specify what it is.</p>
  
  <p>Here are some things I've tried:</p>
  
  <pre><code>#include &lt;iostream&gt;    
  #include &lt;windows.h&gt;
  #include &lt;string&gt;
  
  int main()
  {
     std::string comNum;
     std::cout &lt;&lt; "\n\nEnter the port (ex: COM20): ";
     std::cin &gt;&gt; comNum;
     std::string comPrefix = "\\\\.\\";
     std::string comID = comPrefix+comNum;
  
     HANDLE hSerial;
  
     hSerial = CreateFile( comID,
                           GENERIC_READ | GENERIC_WRITE,
                           0,
                           0,
                           OPEN_EXISTING,
                           FILE_ATTRIBUTE_NORMAL,
                           0);`
  
     return 0;
  }
  </code></pre>
  
  <p>This does not compile and returns the error: <strong>error C2664: 'CreateFileW' : cannot convert parameter 1 from 'std::string' to 'LPCWSTR'</strong></p>
  
  <p>I thought maybe specifying CreateFileA would work then, but that gave basically the same error.</p>
  
  <p>I also tried :</p>
  
  <pre><code>/*
  everything else the same
  */   
  
  hSerial = CreateFile( TEXT(comID),
                        GENERIC_READ | GENERIC_WRITE,
                        0,
                        0,
                        OPEN_EXISTING,
                        FILE_ATTRIBUTE_NORMAL,
                        0);`
  </code></pre>
  
  <p>which also does not compile and returns: <strong>error C2065: 'LcomID' : undeclared identifier</strong></p>
  
  <p>I am not much of an expert but I have been working on this for a while now.  Can someone tell me how to replace <code>L"\\\\.\\COM20"</code> in such a way that the user can specify the comport and so that CreateFile will still work?  Thanks!</p>