ExpandEnvironmentStrings Not Expanding My Variables

只愿长相守 提交于 2019-12-24 03:21:07

问题


I have a process under the Run key in the registry. It is trying to access an environment variable that I have defined in a previous session. I'm using ExpandEnvironmentStrings to expand the variable within a path. The environment variable is a user profile variable. When I run my process on the command line it does not expand as well. If I call 'set' I can see the variable.

Some code...

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

When debugging Output path is exactly the same as Path. No error code is returned.

What is goin on?


回答1:


One problem is that you are providing the wrong parameters to ExpandEnvironmentStrings and then using a cast to hide that fact (although you do need a cast to get the correct type out of a CString).

You are also using the wrong value for the last parameter. That should be the size of the output buffer, not the size of the input length (from the documentation the maximum number of characters that can be stored in the buffer pointed to by the lpDst parameter)

Putting that altogether, you want:

ExpandEnvironmentStrings((LPCTSTR)strPath,
                         cOutputPath,
                         sizeof(cOuputPath) / sizeof(*cOutputPath));



回答2:


I don't see any error checking code in your snippet, you don't assert the return value. If there's a problem, you'd never discover it. Also, you are using ANSI strings, beware of the weirdo requirement for the nSize argument (1 extra).




回答3:


What about buffersize ? Is it initialized - to the right value ?

The documentation states that If the destination buffer is too small to hold the expanded string, the return value is the required buffer size, in characters.



来源:https://stackoverflow.com/questions/2404103/expandenvironmentstrings-not-expanding-my-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!