C ++: using std :: wstring in an API function

I am using the SHGetSpecialFolderLocation API function . My app is set to "Use Unicode Character Set".

Here is what I still have:

int main ( int, char ** )
{
    LPITEMIDLIST pidl;
    HRESULT hr = SHGetSpecialFolderLocation(NULL, CSIDL_PERSONAL, &pidl);


    /* Confused at this point */
    wstring wstrPath;

    wstrPath.resize ( _MAX_PATH );
    BOOL f = SHGetPathFromIDList(pidl, wstrPath.c_str () );
    /* End confusion */

The error I am getting is:

error C2664: 'SHGetPathFromIDListW' : cannot convert parameter 2 from 'const wchar_t *' to 'LPWSTR'

Can anyone help? What is the correct C ++ way to do this?

Thank!

+3
source share
5 answers

The second parameter is the out parameter, so you cannot just pass c_str(which is const) directly. This would probably be the easiest to do:

wchar_t wstrPath[MAX_PATH];
BOOL f = SHGetPathFromIDList(pidl, wstrPath);

MAX_PATH currently has 260 characters.

+6
source

std::basic_string::c_str() . , - :

wstring wstrPath;
wstrPath.resize( MAX_PATH );
BOOL f = SHGetPathFromIDList(pidl, &wstrPath[0]);
wstrPath.erase(
   std::find(wstrPath.begin(), wstrPath.end(), L'\0'), wstrPath.end()
); //Throw away unused buffer space

EDIT: , C ( , ):

wstring wstrPath;
wstrPath.resize( MAX_PATH );
BOOL f = SHGetPathFromIDList(pidl, &wstrPath[0]);
wstrPath.resize(wcslen(wstrPath.c_str()));
+1

wstring::c_str() const wchar_t* . LPWSTR const, out. . - :

wchar_t buf[MAX_PATH] = {0};
BOOL f = SHGetPathFromIDList( pidl, buf );
wstring wstrPath = buf;
+1

wstring:: c_str() . - wchar_t wstring:

wchar_t buf[MAX_PATH];
BOOL f = SHGetPathFromIDList(pidl, buf );
wstring wstrPath(buf);
0

You can get the address of the element of the 1st array in basic_string as a pointer to the written string data. Although the C ++ standard does not guarantee that this memory block must be contiguous, it is safe in all known implementations ( How bad the code is using std :: basic_string as a contiguous buffer ).

std::wstring path(_MAX_PATH, L'\0');
BOOL f = SHGetPathFromIDList(pidl, &path[0]);
0
source

Source: https://habr.com/ru/post/1752184/


All Articles