C++:在 API 函数中使用 std::wstring
我正在使用 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++ 方法是什么?
谢谢!
I'm using the SHGetSpecialFolderLocation API function. My application is set to "Use Unicode Character Set".
Here's what I have so far:
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'm getting is:
error C2664: 'SHGetPathFromIDListW' : cannot convert parameter 2 from 'const wchar_t *' to 'LPWSTR'
Can someone help? What's the proper C++ way to do this?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
第二个参数是一个 out 参数,因此您不能直接传递
c_str
(即const
)。最简单的做法可能是:MAX_PATH
当前为 260 个字符。The second parameter is an out parameter, so you can't just pass
c_str
(which isconst
) directly. It would probably be simplest just to do:MAX_PATH
is currently 260 characters.wstring::c_str()
返回const wchar_t*
并且是只读。LPWSTR
不是const
类型,并且该参数是输出参数。您需要自己分配缓冲区。你可以这样做:wstring::c_str()
returnsconst wchar_t*
and is read only.LPWSTR
is not aconst
type, and that parameter is an out parameter. You will need to allocate the buffer yourself. You could do something like this:您可以获取 basic_string 中第一个数组项的地址作为指向可写字符串数据的指针。尽管 C++ 标准不保证该内存块必须是连续的,但这在所有已知的实现中都是安全的 (使用 std::basic_string 作为连续缓冲区的代码有多糟糕)。
You can get address of 1st array item in basic_string as pointer to writable string data. Although C++ standard does not guarantee that this block of memory must be continuous this is safe in all known implementations (How bad is code using std::basic_string as a contiguous buffer).
std::basic_string::c_str()
返回一个常量缓冲区到它的内存中。如果你想修改字符串,你必须这样做:编辑:如果你不害怕 C 库,这个应该也可以工作(尽管我没有像我一样测试过它)已经测试了上面的实现):
std::basic_string::c_str()
returns a constant buffer to it's memory. If you want to modify the string, you'd have to do something like this:EDIT: This should also work if you're not afraid of C libraries (though I've not tested it like I've tested the implementation above):
wstring::c_str() 不允许您以这种方式修改其内部缓冲区。最简单的解决方法是自己创建一个 wchar_t 缓冲区,并将其传递给 wstring 构造函数:
wstring::c_str() does not let you modify its internal buffer in this way. Your easiest workaround is to create a wchar_t buffer yourself, and the pass that to the wstring constructor: