C ++: using std :: wstring in funzione API
Domanda
Sto utilizzando il SHGetSpecialFolderLocation funzione API. La mia domanda è impostato su "Use Unicode Character Set".
Ecco quello che ho finora:
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 */
L'errore che sto ottenendo è:
error C2664: 'SHGetPathFromIDListW' : cannot convert parameter 2 from 'const wchar_t *' to 'LPWSTR'
aiuto qualcuno Can? Qual è il corretto C ++ modo per fare questo?
Grazie!
Soluzione
Il secondo parametro è un il parametro, quindi non si può semplicemente passare c_str
(che è const
) direttamente. Probabilmente sarebbe più semplice solo per fare:
wchar_t wstrPath[MAX_PATH];
BOOL f = SHGetPathFromIDList(pidl, wstrPath);
MAX_PATH
è attualmente 260 caratteri.
Altri suggerimenti
ritorna wstring::c_str()
const wchar_t*
ed è sola lettura . LPWSTR
non è un tipo const
, e tale parametro è un parametro out. Sarà necessario allocare il buffer da soli. Si potrebbe fare qualcosa di simile:
wchar_t buf[MAX_PATH] = {0};
BOOL f = SHGetPathFromIDList( pidl, buf );
wstring wstrPath = buf;
È possibile ottenere l'indirizzo del primo elemento dell'array in basic_string come puntatore a dati di stringa scrivibili. Sebbene C ++ standard non garantisce che questo blocco di memoria deve essere continuo questo è sicuro in tutte le implementazioni noti ( quanto è grave il codice utilizzando std :: basic_string come buffer contigui ).
std::wstring path(_MAX_PATH, L'\0');
BOOL f = SHGetPathFromIDList(pidl, &path[0]);
ritorna std::basic_string::c_str()
un costante tampone ad esso di memoria. Se si vuole modificare la stringa, che avrebbe dovuto fare qualcosa di simile:
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: Questo dovrebbe anche il lavoro se non hai paura di librerie C (anche se ho non testato come ho avuto modo di provare l'attuazione di cui sopra):
wstring wstrPath;
wstrPath.resize( MAX_PATH );
BOOL f = SHGetPathFromIDList(pidl, &wstrPath[0]);
wstrPath.resize(wcslen(wstrPath.c_str()));
wstring :: c_str () non consentono di modificare il suo buffer interno in questo modo. La vostra soluzione più semplice è quello di creare un wchar_t tampone te stesso, e il valico che al costruttore wstring:
wchar_t buf[MAX_PATH];
BOOL f = SHGetPathFromIDList(pidl, buf );
wstring wstrPath(buf);