Search code examples
c#environment-variablespinvoke

Changes via SetEnvironmentVariable do not take effect in library that uses getenv


I have a simple c# application that is binding to a library compile with mingnu compiler toolset. I can easily call the functions in the library without issue.

However the library calls getenv to set itself up this environment variable needs to be set for the library to work correctly so I am using Environment.SetEnvironmentVariable however the library cannot retrieve the value I have set.


Solution

  • getenv makes a copy of the environment variable block of the process on startup. Any subsequent changes via SetEnvironmentVariable will not be reflected in the block of variables used by getenv. You will need to PInvoke the setenv function to have the adjusted the value reflected in subsequent putenv calls.

    See: http://msdn.microsoft.com/en-us/library/tehxacec(VS.71).aspx

    getenv and _putenv use the copy of the environment pointed to by the global variable _environ to access the environment. getenv operates only on the data structures accessible to the run-time library and not on the environment "segment" created for the process by the operating system. Therefore, programs that use the envp argument to main or wmain may retrieve invalid information.