问题描述
我有一个 EXE,它在启动时通过 Windows API SetEnvironmentVariable()
环境变量(即:MAGICK_CODER_MODULE_PATH=xxx
)>.
I have an EXE which, at startup, sets an environment variable (ie: MAGICK_CODER_MODULE_PATH=xxx
) via the Windows API SetEnvironmentVariable()
.
当我在进程资源管理器(来自 SysInternals)中查看设置为我的 EXE 的环境变量列表时,我可以看到我之前设置的环境变量(MAGICK_CODER_MODULE_PATH
),所以一切看起来都很好点.
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.
然后我指示我的 EXE 通过 LoadLibrary()
加载一个 DLL.稍后,当此 DLL 尝试通过 getenv("MAGICK_CODER_MODULE_PATH")
获取我的环境变量的值时,问题出现了:它返回 NULL!这怎么可能?看起来 getenv()
忽略了我之前用 SetEnvironmentVariable()
设置的值.
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()
.
注意:
- 使用旧版本的 Visual Studio 编译 DLL 时似乎不会发生这种情况(可能与
vcruntime140.dll
/msvcp140.dll
相关). - 如果我打开命令提示符,请执行
@SET MAGICK_CODER_MODULE_PATH=xxx
,然后从该命令提示符启动我的 EXE,然后一切正常:DLL 成功获取了MAGICK_CODER_MODULE_PATH 的值
通过getenv()
.
- 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 ofMAGICK_CODER_MODULE_PATH
viagetenv()
.
推荐答案
您正在混合 API:Windows 的 SetEnvironmentVariable
绕过 C++ 运行时,因此存储在您的环境中的副本程序未更新.后面的 getenv
调用会查看此副本,但未找到您的更改.
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.
对两个调用使用相同的 API 级别.getenv
和 _putenv代码>
,或使用 Windows API GetEnvironmentVariable
和 SetEnvironmentVariable
.
Use the same API level for both calls. Either getenv
and _putenv
, or use the Windows API GetEnvironmentVariable
and SetEnvironmentVariable
.
这篇关于SetEnvironmentVariable() 似乎没有设置可以通过 getenv() 检索的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!