3

I have a DLL obtaining startup options using getenv (<stdlib.h>) call. I would like to set that variable in the same process, before opening the DLL, so that it is accessible via getenv. Which function should I use to set it?

I learned that there are two sets of env vars under windows: one is manipulated via win32 API (GetEnvironemntVariable, SetEnvironmentVariable), another one can be read using getenv, and probably set via _putenv, is that the one I should use?

Is this function accessible from python, perhaps via ctypes?

2 Answers 2

2

The current ~VS2019 situation appears to be:

  • The calls to the getenv function retrieve the values from a block the MS CRT initializes at load time.
  • Calls to GetEnvironmentVariable retrieve the value from the process environment block.
  • Calls to SetEnvironmentVariable update only the value from the process environment block. These changes will not be seen by getenv.
  • Calls to putenv update both the value in the CRT block and also additionally call Win32 SetEnvironmentVariable to update the process environment block.

So, actually regardless of what you use it for:

  • Use _wputenv_s to set the env var - it will update both.
  • Use ::GetEnvironmentVariableW to read: It will read from the environment block, which will contain the value regardless of which method was used.

Regarding getenv

If the code using getenv is using the same MS CRT that your code -- that is, the code is dynamically linked to the CRT and actually uses the same version as you, then you can always use putenv.

If the DLL (AND its CRT) is dynamically or delay-loaded and you are able to call putenv before the dll is loaded, then you can use it.

(This is conjecture, I have not tested this exactly:) If the DLL is already loaded in you process and it uses a statically linked CRT, or another CRT than the one you are using, than the environment data for its getenv call is already loaded up, an nothing that you do on your side of the DLL boundary will change that. Out of luck in this case I guess.

Ref:

Sign up to request clarification or add additional context in comments.

Comments

1

As the question is tagged with Python, the blessed way to manage environment variables in Python is to update the os.environ mapping.

Because the doc for os.putenv() says:

Assignments to items in os.environ are automatically translated into corresponding calls to putenv(); however, calls to putenv() don’t update os.environ, so it is actually preferable to assign to items of os.environ.

1 Comment

Fascinating. So in Python on Windows we have 3 layers os.environ -> mscrt envorinment data -> Win32 Process Env Block. :-D

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.