3

我正在使用SHGetSpecialFolderLocation API 函数。我的应用程序设置为“使用 Unicode 字符集”。

这是我到目前为止所拥有的:

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 */

我得到的错误是:

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

有人可以帮忙吗?执行此操作的正确 C++ 方法是什么?

谢谢!

4

5 回答 5

6

第二个参数是out参数,所以不能直接传递c_str(即const)。这样做可能是最简单的:

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

MAX_PATH目前是 260 个字符。

于 2010-06-29T01:41:01.630 回答
1

您可以获取 basic_string 中第一个数组项的地址作为指向可写字符串数据的指针。尽管 C++ 标准不保证此内存块必须是连续的,但这在所有已知实现中都是安全的(使用 std::basic_string 作为连续缓冲区的代码有多糟糕)。

std::wstring path(_MAX_PATH, L'\0');
BOOL f = SHGetPathFromIDList(pidl, &path[0]);
于 2010-06-29T06:48:25.863 回答
1

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

编辑:如果您不害怕 C 库,这也应该有效(尽管我没有像测试上面的实现那样测试它):

wstring wstrPath;
wstrPath.resize( MAX_PATH );
BOOL f = SHGetPathFromIDList(pidl, &wstrPath[0]);
wstrPath.resize(wcslen(wstrPath.c_str()));
于 2010-06-29T01:44:50.147 回答
1

wstring::c_str()返回const wchar_t*并且是只读的。LPWSTR不是const类型,并且该参数是输出参数。您需要自己分配缓冲区。你可以这样做:

wchar_t buf[MAX_PATH] = {0};
BOOL f = SHGetPathFromIDList( pidl, buf );
wstring wstrPath = buf;
于 2010-06-29T01:45:41.853 回答
0

wstring::c_str() 不允许您以这种方式修改其内部缓冲区。您最简单的解决方法是自己创建一个 wchar_t 缓冲区,并将其传递给 wstring 构造函数:

wchar_t buf[MAX_PATH];
BOOL f = SHGetPathFromIDList(pidl, buf );
wstring wstrPath(buf);
于 2010-06-29T01:46:05.713 回答