首页 > 解决方案 > C++ ExpandEnvironmentStringsForUser 函数有时会返回错误值

问题描述

我正在使用ExpandEnvironmentStringsForUser函数来扩展包含环境变量的目录。但是,返回的值有时是错误的。

我的进程以系统权限运行。

例如:

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)

有谁知道输出不稳定的原因?

标签: c++windowswinapi

解决方案


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);

推荐阅读