How do I convert PWSTR to string in C++?

前端 未结 5 848
南笙
南笙 2020-12-11 04:41

I have the following code:

// Fetch Local App Data folder path.
PWSTR localAppData = (PWSTR) malloc(128);
SHGetKnownFolderPath(FOLDERID_LocalAppData, 0, NULL         


        
5条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-11 05:14

    PWSTR is a pointer to a wide-character string. You need

    // Fetch Local App Data folder path.
    PWSTR localAppData = (PWSTR) malloc(128);
    SHGetKnownFolderPath(FOLDERID_LocalAppData, 0, NULL, &localAppData);
    
    wstringstream ss;
    ss << localAppData << L"/Google/Chrome/Application/chrome.exe";
    

    Also, malloc argument indicates the number of bytes to allocate, so you're allocating a buffer that can only hold 64 wide characters (including the NULL character). You might want to use malloc( 128 * sizeof(wchar_t) ).

    EDIT:
    From the documentation for SHGetKnownFolderPath

    ppszPath When this method returns, contains the address of a pointer to a null-terminated Unicode string that specifies the path of the known folder. The calling process is responsible for freeing this resource once it is no longer needed by calling CoTaskMemFree

    So you shouldn't be allocating any memory for the last argument for the function.

    wchar_t *localAppData = NULL;
    ::SHGetKnownFolderPath(FOLDERID_LocalAppData, 0, NULL, &localAppData);
    
    wstringstream ss;
    ss << localAppData << L"/Google/Chrome/Application/chrome.exe";
    ::CoTaskMemFree(localAppData);
    

提交回复
热议问题