Home > database >  SetEnvironmentVariable() does not seem to set values that can be retrieved by getenv()
SetEnvironmentVariable() does not seem to set values that can be retrieved by getenv()

Time:09-16

I have an EXE which, at startup, sets an environment variable (ie: MAGICK_CODER_MODULE_PATH=xxx) via the Windows API SetEnvironmentVariable().

When I look in Process Explorer (from SysInternals) at the list of environment variables set to my EXE I can see the environment variable I just set before (MAGICK_CODER_MODULE_PATH), so everything looks good at this point.

Then I instruct my EXE to load a DLL via LoadLibrary(). The problem arises a little later when this DLL tries to get the value of my environment variable via getenv("MAGICK_CODER_MODULE_PATH"): it returns NULL! How could this be possible? It looks like getenv() ignores the value I just set before with SetEnvironmentVariable().

Note:

  • This seems to not happen when the DLL is compiled with an old version of Visual Studio (maybe related to vcruntime140.dll / msvcp140.dll).
  • If I open a command prompt, do @SET MAGICK_CODER_MODULE_PATH=xxx, and from this command prompt then launch my EXE, then everything works fine: the DLL successfully gets the value of MAGICK_CODER_MODULE_PATH via getenv().

CodePudding user response:

You're mixing APIs: Windows' SetEnvironmentVariable bypasses the C runtime, so that the copy of the environment that is stored in your program is not updated. The later getenv call looks into this copy and doesn't find your change.

Use the same API level for both calls. Either getenv and _putenv, or use the Windows API GetEnvironmentVariable and SetEnvironmentVariable.

  • Related