views:

416

answers:

5

I have a string in char* format and would like to convert it to wchar_t*, to pass to a Windows function.

+3  A: 

You can use ATL macros A2W or CA2W.

ssg
+6  A: 

Does this little function help?

#include <cstdlib>

int mbstowcs(wchar_t *out, const char *in, size_t size);

Also see the C++ reference

schnaader
+6  A: 

If you don't want to link against the C runtime library, use the MultiByteToWideChar API call, e.g:

const size_t WCHARBUF = 100;
const char s[] = "HELLO";
wchar_t  wszDest[WCHARBUF];
MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, szSource, -1, wszDest, WCHARBUF);
Hernán
Depending on where your string comes from, you might also want to consider CP_UTF8 instead of CP_ACP. It can store all Unicode characters.
asveikau
+2  A: 

the Windows SDK specifies 2 functions in kernel32.lib for converting strings from and to a wide character set. those are MultiByteToWideChar() and WideCharToMultiByte().

please note that, unlike the function name suggest, the string does not necessarily use a multi-byte character set, but can be a simple ANSI string. alse note that those functions understand UTF-7 and UTF-8 as a multi-byte character set. the wide char character set is always UTF-16.

Adrien Plisson
+1  A: 

schnaader's answer use the conversion defined by the current C locale, this one uses the C++ locale interface (who said that it was simple?)

std::wstring widen(std::string const& s, std::locale loc)
{
    std::char_traits<wchar_t>::state_type state = { 0 };

    typedef std::codecvt<wchar_t, char, std::char_traits<wchar_t>::state_type >
        ConverterFacet;

    ConverterFacet const& converter(std::use_facet<ConverterFacet>(loc));

    char const* nextToRead = s.data();
    wchar_t buffer[BUFSIZ];
    wchar_t* nextToWrite;
    std::codecvt_base::result result;
    std::wstring wresult;

    while ((result
            = converter.in
                  (state,
                   nextToRead, s.data()+s.size(), nextToRead,
                   buffer, buffer+sizeof(buffer)/sizeof(*buffer), nextToWrite))
           == std::codecvt_base::partial)
    {
        wresult.append(buffer, nextToWrite);
    }

    if (result == std::codecvt_base::error) {
        throw std::runtime_error("Encoding error");
    }
    wresult.append(buffer, nextToWrite);
    return wresult;
}
AProgrammer