some code for a change

I’ve written this function a zillion times, so I decided to post it on my blog. Yes, it could do more error checking (what if that new returns a NULL? what if an exception is thrown?). But it does more than zero error checking, so there you go. This is super useful if you are getting ANSI code paths from legacy APIs or if you are using boost::filesystem::path to store paths in a platform independent way (until the new boost comes out).

This particular version isn’t battle tested (yet), but it does work.

// convert a path from ANSI to UNICODE on windows using std::strings
// useful for converting a boost::filesystem::path into a wpath,
// until those APIs get merged
std::wstring convertStringToWString( std::string in )
{
    if (in.length() == 0 )
    {
        return std::wstring();
    }

    UINT wStringLength = MultiByteToWideChar( CP_ACP, 0, in.c_str(), -1, NULL, 0);
    if (wStringLength==0)
    {
        return std::wstring();
    }

    LPWSTR widestr = new WCHAR[wStringLength];
    wStringLength = MultiByteToWideChar( CP_ACP, 0, in.c_str(), -1, widestr, wStringLength );
    if ( wStringLength ==0 )
    {
        delete[] widestr;
        return std::wstring();
    }

    std::wstring returnVal = std::wstring( widestr );
    delete[] widestr;

    return returnVal;
}