Are there any windows programmers around? I’m having some issues with CreateFile() from the win32 api. I’m compiling with MinGW and it’s giving me the following error:
port = CreateFile(dev.c_str(),GENERIC_READ|GENERIC_WRITE,0,0,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,0);
dev is a std::string. I’m new to windows programming, so I might be missing something. All the documentation I can find, however, says that the first parameter should be a null terminated string. c_str() is supposed to give me that. I’ve also tried to use the following and I get an idential error:
port = CreateFile(“COM1”,GENERIC_READ|GENERIC_WRITE,0,0,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,0);
Which leads me to believe that it’s not that simple.
I figured it out. My Makefile was trying to be helpful and defined UNICODE in the compiler options. Apparently, the compiler doesn’t like that. I’m not really sure why it’s defined or why it works without it, but it taking it out fixed the problem.
Just FYI, this is because standard ASCII strings (char*) use 8 bits per character but Unicode (WCHAR*) use more (16 bits I believe). The compiler correctly stopped you from passing a string of 16 bit characters to a function that is expecting 8 bits per character. If it hadn’t, your program would have behaved very unexpectedly.
To add just a little bit more information to this, when UNICODE is defined, WCHAR is 16-bits but when it is not defined WCHAR is only 8-bits (the same as a regular char). This is why the cast was failing.
I knew it had to be something like that because of the CreateFileW, and the WCHAR* in the error message. I assumed, though, that you needed wide character strings for some reason, and I was looking around for a way to create a wide string from an 8 bit one.