views:

467

answers:

4

Hello,

This is my procedure:

bool Open(std::string filename)
{
    ...
    HANDLE hFile = CreateFile(filename.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
    ...
}

Error:'CreateFileW' : cannot convert parameter 1 from 'const char *' to 'LPCWSTR' Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast

Where is the problem?

+1  A: 

It looks like you are compiling with Unicode support turned on. You may want to turn it off, or if not use std::wstring instead of std::string.

As others have suggested, you could call CreateFileA directly, but I'd strongly suggest you not do this - you will end up with an unmaintanable collection of Unicode and non-Unicode function calls.

anon
How do I turn off the unicode support?
John
Depends on your development platform.
anon
+10  A: 

A std::string consists of an array of char's, and so the c_str function returns a const char*.

A LPCWSTR is a Long Pointer to a Constant Wide String, or in other words, const wchar_t*.

So you have a couple of options. Either get the filename as a wide string (std::wstring), or specify that you want the non-wide version of CreateFile instead. That can be done either by calling CreateFileA or disabling UNICODE in your project settings.

CreateFile is a macro which either resolves to CreateFileA (the char version) or CreateFileW (the wide char version) depending on whether or not unicode is enabled.

jalf
Note: The right solution, especially if this is new software, is to use std::wstring.
Greg D
+2  A: 

You have specified std::string, whose character type is char. And the code you're using CreateFile() in must be being compiled under the definition of the pre-processor symbol UNICODE, since that selects the actual underlying function CreateFileW().

Either get rid of the UNICODE definition, or explicitly use CreateFileA().

dcw
A: 

The problem is you are trying to pass char* to a function requiring wchar_t*

You could write a function to convert string into wstring:

wstring Widen( const string& str );

Then you could call CreateFile like this:

HANDLE hFile = CreateFile( Widen(filename).c_str(), etc. );

Another technique I've seen used is to conditionally define tstring to be either string or wstring depending on the Unicode setting, and use tstring everywhere in your code.

bool Open(tstring filename)
{
    ...
    HANDLE hFile = CreateFile( filename.c_str(), etc. );
    ...
}

It's a bit of a thorny issue I'm afraid and the best solution for you is something only you can decide. However, I'd agree with Neil and steer clear of directly calling CreateFileA as that will leave you in a mess eventually.

markh44