ExpandEnvironmentStrings不扩展我的变量

Ada*_*oll 2 c++ winapi environment-variables

我在注册表中的Run键下有一个进程.它正在尝试访问我在上一个会话中定义的环境变量.我正在使用ExpandEnvironmentStrings来扩展路径中的变量.环境变量是用户配置文件变量.当我在命令行上运行我的进程时,它也不会扩展.如果我调用'set',我可以看到变量.

一些代码......

CString strPath = "\\\\server\\%share%"
TCHAR cOutputPath[32000]; 
DWORD result = ExpandEnvironmentStrings((LPSTR)&strPath, (LPSTR)&cOutputPath,  _tcslen(strPath) + 1);
 if ( !result )
 {
  int lastError = GetLastError();
  pLog->Log(_T( "Failed to expand environment strings. GetLastError=%d"),1, lastError);
 }
Run Code Online (Sandbox Code Playgroud)

调试时输出路径与Path完全相同.没有返回错误代码.

什么是布莱恩?

R S*_*hko 8

一个问题是你提供了错误的参数ExpandEnvironmentStrings,然后使用强制转换来隐藏这个事实(虽然你需要一个强制转换来获得正确的类型CString).

您还使用了错误的值作为最后一个参数.那应该是输出缓冲区的大小,而不是输入长度的大小(来自文档 the maximum number of characters that can be stored in the buffer pointed to by the lpDst parameter)

总而言之,你想要:

ExpandEnvironmentStrings((LPCTSTR)strPath,
                         cOutputPath,
                         sizeof(cOuputPath) / sizeof(*cOutputPath));
Run Code Online (Sandbox Code Playgroud)

  • 就在头上 谢谢。我只需要花时间从事C ++业务... .Net使我变得懒惰... (2认同)