Why setenv and getenv behavior changed for MEX functions between R2016b and R2017b?

6 views (last 30 days)
I noticed a change in setenv or getenv behavior between R2016b and R2017b in Windows 10.
It's something similar to what already discussed in this previous question , but in my case I have different results with different Matlab versions: the environment variable change is visible in MEX in R2016b but it's not in R2017b.
Here the MEX function used for testing, basically a copy taken from the previous question called test_env_vars.cpp:
#include "mex.h"
void mexFunction(int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[])
{
printf("OS : %s\n", getenv("OS"));
printf("AAA : %s\n", getenv("AAA"));
}
Now running the following in Matlab R2016b I get:
>> version
ans =
9.1.0.441655 (R2016b)
>> test_env_vars
OS : Windows_NT
AAA : (null)
>> setenv('AAA','pizza')
>> getenv('AAA')
ans =
pizza
>> test_env_vars
OS : Windows_NT
AAA : pizza
So getenv in MEX code sees my environment variable changed performed within Matlab.
Instead in Matlab R2017b (same machine, same OS) I get:
>> version
ans =
'9.3.0.713579 (R2017b)'
>> test_env_vars
OS : Windows_NT
AAA : (null)
>> setenv('AAA','pizza')
>> getenv('AAA')
ans =
'pizza'
>> test_env_vars
OS : Windows_NT
AAA : (null)
With R2017b the getenv in MEX doesn't see the change.
Can you explain why?
  1 Comment
Luca Maff
Luca Maff on 13 Apr 2018
Exact same behavior with R2018a:
>> version
ans =
'9.4.0.813654 (R2018a)'
>> test_env_vars
OS : Windows_NT
AAA : (null)
>> setenv('AAA','pizza')
>> getenv('AAA')
ans =
'pizza'
>> test_env_vars
OS : Windows_NT
AAA : (null)
Any idea?

Sign in to comment.

Answers (1)

Jesse Hopkins
Jesse Hopkins on 22 Feb 2025
I'm also experiencing this in Matlab R2021B on Windows using MinGW compiler. I think it may be related to something within MinGW, as the behavior is normal when I compile using Visual Studio.
I've found a couple workarounds:
Workaround #1: Use the windows-api directly in the mex file to retrieve the environment variable. See GetEnvironmentVariable. This is cumbersome, as the interface is quite different from the c-standard getenv function.
Workaround #2: Write a mex file to set environment variables, and call this instead (or in addition to) Matlab's builtin setenv(). When done this way, envrionment variable set by a MinGW compiled mex file seem to be read by other MinGW mex files. One could play games with path shadowing to override Matlab's builtin setenv to accomplish this seamlessly, however you'll then be nagged by warning 'MATLAB:dispatcher:nameConflict' , 'Function setenv has the same name as a MATLAB builtin. We suggest you rename the function to avoid a potential name conflict.'

Categories

Find more on Write C Functions Callable from MATLAB (MEX Files) in Help Center and File Exchange

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!