c++ - C++ ExpandEnvironmentStringsForUser 函数有时会返回错误值
问题描述
我正在使用ExpandEnvironmentStringsForUser函数来扩展包含环境变量的目录。但是,返回的值有时是错误的。
我的进程以系统权限运行。
例如:
输入字符串:“C:\Users\%username%\Documents\”
输出字符串(可能是以下字符串之一)
C:\Users\cuong.huynh\Documents\(预期输出)
C:\Users\cuong.huynh\AppData\Roaming(错误)
C:\Program Files\Common Files(错误)
我的简要代码如下:
DWORD dwSessionID = WTSGetActiveConsoleSessionId();
WTSQueryUserToken(dwSessionID, &hUserToken);
DuplicateToken(hUserToken, SecurityImpersonation, &hDuplicated)
hToken = hDuplicated;
LPCWSTR DesPath = (StringUtil::StrToWstr(setting)).c_str(); //(input)
wchar_t ExpandedDesPath[MAX_PATH]; //(output)
ExpandEnvironmentStringsForUser(hToken, DesPath, ExpandedDesPath, MAX_PATH - 1)
有谁知道输出不稳定的原因?
解决方案
LPCWSTR DesPath = (StringUtil::StrToWstr(setting)).c_str();`
这会创建一个临时 wstring
的,在分配后立即超出范围DesPath
,留下DestPath
悬空并指向无效内存。您需要先将结果存储StrToWstr()
到局部wstring
变量,然后再调用c_str()
它,因此字符串内存保持在范围内:
wstring wstr = StringUtil::StrToWstr(setting);
LPCWSTR DesPath = wstr.c_str();
否则,StrToWstr().c_str()
直接在 的输入参数中调用ExpandEnvironmentStringsForUser()
:
ExpandEnvironmentStringsForUser(hToken, StringUtil::StrToWstr(setting).c_str(), ExpandedDesPath, MAX_PATH - 1);
推荐阅读
- react-native - 无法解析模块`./../../react-transform-hmr/lib/index.js`
- c++ - 为什么使用 __try __except 会导致函数在 VS C++ /clr 优化版本中不起作用?
- reactjs - 当我尝试从 webpack3 升级到 webpack4 时出错
- symfony - 无法加载类型“app_filter”:类不存在
- c# - 如何在数据网格视图中仅显示日期而不是日期时间
- python - 从 TXT 文件构建字典元组,输出另一个 TXT 文件以测试我的字典的准确性
- ios - 将 Objective-C 框架转换为 Swift - 仍然显示 Objective-C 函数的头文件
- android - camera2 api - 在 Moto Nexus 中没有回调 onImageAvailable
- excel - VBA - 旋转按钮更改列表框中的顺序
- user-interface - Xamarin中按钮之间的奇怪空间