GetEnvironmentStrings
returns a (read-only!) pointer to the start of the environment block for a process.
The block is a contiguous C-style string that contains null-terminated key=value
pairs. The block is ended by an additional null termination.
To make access more convenient, use something like the following function:
typedef std::basic_string<TCHAR> tstring; // Generally convenient
typedef std::map<tstring, tstring> environment_t;
environment_t get_env() {
environment_t env;
auto free = [](LPTCH p) { FreeEnvironmentStrings(p); };
auto env_block = std::unique_ptr<TCHAR, decltype(free)>{
GetEnvironmentStrings(), free};
for (LPTCH i = env_block.get(); *i != T('\0'); ++i) {
tstring key;
tstring value;
for (; *i != T('='); ++i)
key += *i;
++i;
for (; *i != T('\0'); ++i)
value += *i;
env[key] = value;
}
return env;
}
Of course, a proper implementation would encapsulate this in a class, and probably use std::stringstream
rather than manually iterating over the characters, concatenating the strings on char
at a time. But I’m lazy.
Usage is like this:
environment_t env = get_env();
// Now you can write env[T("Var1")] to access a variable.