使用 boost 或标准库扩展 Windows 环境变量

Expand Windows Environment variable with boost or standard library

提问人:Mario 提问时间:9/7/2021 最后编辑:Mario 更新时间:9/7/2021 访问量:223

问:

我想用现代 C++ 编码替换这个函数,也许使用 c++ 17 的 boost 或标准库,是否可以在不调用两次 ExpandEnvironmentStrings 的情况下做到这一点,或者至少摆脱 malloc?

void ReplaceEnviromentVariables(CString& str)
{
    DWORD dwSize;
    TCHAR *pBuff;

    // Get buffer size
    dwSize = ::ExpandEnvironmentStrings(str, NULL, 0);
    if (dwSize == 0)
        return; // error

    pBuff = (TCHAR*)malloc(dwSize * sizeof(TCHAR));

    if (::ExpandEnvironmentStrings(str, pBuff, dwSize))
        str = pBuff;

    free(pBuff);
}
C++ 提升 17 C+ +-标准库

评论

3赞 Remy Lebeau 9/7/2021
"是否可以在不调用两次 ExpandEnvironmentStrings 的情况下做到这一点?- 唯一的方法是预先提供一个非常大的缓冲区,即使这样也不能保证你足够大。调用两次没有错(许多 Win32 API 都设计为以这种方式工作)。真正的问题是 ,它真的不应该在 C++ 中使用,所以你应该茁壮成长来代替它,比如用 或 。ExpandEnvironmentStrings()ExpandEnvironmentStrings()malloc()std::vectorstd::(w)string
0赞 Mario 9/7/2021
@RemyLebeau谢谢!但至少要摆脱 malloc
1赞 Phil1970 9/7/2021
如果您使用 Microsoft ,那么已经有 CString::GetBuffer 用于此目的。顺便说一句,你应该在第一次使用之前声明变量,并停止其他 C 习惯,如 malloc/free。CString
0赞 Mario 9/7/2021
@Phil1970你是对的:)我忘了

答: 暂无答案