Freakishly
Freakishly

Reputation: 1571

How can I convert PCWSTR to a char[] or wchar_t[]

I'm trying to create a file, where one of the parameters has been passed in to the method and is of the type PCWSTR. My code creates a .url file and saves the Url into the file:

        wchar_t array1[] = "[InternetShortcut]\nURL=";
        wchar_t array2[] = pdwFavoriteUrl;
        wchar_t * DataBuffer = new wchar_t[wcslen(array1) + std::strlen(array2) + 1];
        std::strcpy(DataBuffer,array1);
        std::strcat(DataBuffer,array2);

        // Write data to file
        DWORD dwBytesToWrite = (DWORD)strlen(DataBuffer);
        DWORD dwBytesWritten = 0;
        BOOL bErrorFlag = FALSE;

        bErrorFlag = WriteFile(hFile, DataBuffer, dwBytesToWrite, &dwBytesWritten, NULL);

        if (FALSE == bErrorFlag)
        {
            // Log error
            hr = E_FAIL;
        }
        else
        {
            if (dwBytesWritten != dwBytesToWrite)
            {
                // Log error
                hr = E_FAIL;
            }
            else
            {
                // Log success
                hr = S_OK;
                //_tprintf(TEXT("Wrote %d bytes to %s successfully.\n"), dwBytesWritten, argv[1]);
            }
        }

        CloseHandle(hFile);

I am aware that the code will not compile as-is, since there are conflicting versions of unicode and non-unicode string methods. The line of interest is this one:

wchar_t array2[] = pdwFavoriteUrl;

pdwFavoriteUrl is of type PCWSTR and there is no way around it. Please help convert it to wchar_t[] (preferred) or char[].

Upvotes: 0

Views: 5452

Answers (2)

Harry Johnston
Harry Johnston

Reputation: 36318

Remove

wchar_t array2[] = pdwFavoriteUrl;

and change the call to strcat to

std::strcat(DataBuffer, pwdFavoriteUrl);

(and similarly, replace array2 with pwdFavoriteUrl in the call to strlen.)

Note that PCWSTR is just

typedef const wchar_t * PCWSTR;

Upvotes: 0

LihO
LihO

Reputation: 42083

AFAIK PCWSTR is just an alias for wchar_t* and in case it is null-terminated that the simplest thing to do would be using it to construct an object of type std::wstring. Just pass it to constructor:

PCWSTR wcstr = L"My String";
std::wstring wstr(wcstr);

and work with std::wstring objects instead of doing evil stuff such as:

wchar_t * DataBuffer = new wchar_t[wcslen(array1) + std::strlen(array2) + 1];

which will probably bring you nothing but unpleasant problems and memory leaks.

Upvotes: 1

Related Questions