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

社会主义新天地 提交于 2019-12-23 12:56:35

问题


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.


回答1:


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 getenv 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."




回答2:


You can import the _putenv_s function into your C# class to set the environment variable in a way that will be visible to native C++ code.

This uses InteropServices:

using System.Runtime.InteropServices;

public class TestEnv
{
    [DllImport( "msvcrt.dll" )]
    public static extern int _putenv_s( string e, string v );

    public TestEnv()
    {
        _putenv_s( "ENV_VAR", "VALUE" );
    }
}

There is a tutorial here that may be helpful.




回答3:


You just set environment variable after create a native C++ object, then the C++ can get the value of environment variable using getenv function or ACE_OS::getenv().



来源:https://stackoverflow.com/questions/4788398/changes-via-setenvironmentvariable-do-not-take-effect-in-library-that-uses-geten

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