我正在开发一个 UTF-8 API,它应该独立于操作系统透明地工作。
为此,我正在替换getenvbyGetEnvironmentVariableW并char** env传递给mainby GetEnvironmentStringsW。
为了确保一切正确,我遍历env数组并检查每个值GetEnvironmentVariableW以确保它们匹配。
这适用于任何地方,但对于 MinGW/MSYS 来说,它对于环境变量tempwheregetenv = C:\msys64\tmp和GetEnvironmentStringsW返回失败C:\Users\appveyor\AppData\Local\Temp\1
我使用c:\msys64\usr\bin\env MSYSTEM=MINGW32 c:\msys64\usr\bin\bash -l -c "echo $temp"(类似于构建/测试的运行方式)验证了该值,并在那里返回C:\Users\appveyor\AppData\Local\Temp\1。
所以它似乎GetEnvironmentVariableW返回一个不同/错误的值。
这怎么可能?我可以避免这种情况吗?
测试代码如下:
for(char** e = env; *e != 0; e++)
{
const char* key_begin = *e;
const char* key_end = strchr(key_begin, '=');
std::string key = std::string(key_begin, key_end);
std::string value = key_end + 1;
const char* env_value = boost::nowide::getenv(key.c_str());
TEST_EQ(env_value, value);
}
getenv 函数在哪里(在没有错误检查等情况下减少):
char* getenv(const char* key)
{
static const size_t buf_size = 64;
wchar_t buf[buf_size];
GetEnvironmentVariableW(widen(key), buf, buf_size);
return narrow(buf);
}
编辑:我能够用以下最少的代码重现这个:
#include <iostream>
#include <windows.h>
#include <string>
int main()
{
const size_t buf_size = 4000;
char buf[buf_size];
GetEnvironmentVariable("temp", buf, buf_size);
std::cout << buf << std::endl;
return 0;
}
当编译(例如在 MSVC 中)并temp=Foobar ./a.out在 Windows 上的 Git bash 中运行时,它会打印C:\Users\alex\AppData\Local\Tempnot Foobar. 在 GetEnvironmentStrings 中的值是正确的