MEX application: integer value is kept in memory between runs

1 view (last 30 days)
If I create the following C file:
#include "mex.h"
unsigned int inputCounter = 0;
void mexFunction(int nlhs, mxArray *plhs[], int nrhs,
const mxArray *prhs[])
{
mexPrintf("inputCounter = %d\n", inputCounter);
inputCounter ++;
}
And compile and run it in Matlab with
mex MexIntegerInit.c
MexIntegerInit
MexIntegerInit
MexIntegerInit
I get the following output:
Building with 'MinGW64 Compiler (C)'.
MEX completed successfully.
inputCounter = 0
inputCounter = 1
inputCounter = 2
However, if I compile outside of Matlab with the same compiler (MinGW64), and run it as a standalone without re-compiling between runs, the value is not incremented.
Is this undefined behavior?

Accepted Answer

Walter Roberson
Walter Roberson on 30 Jan 2019
no the behaviour is defined . When called inside MATLAB it is being called as a subroutine of the MATLAB process which continues to exist after the call. When called standalone each call creates a process , runs, and terminates returning the memory to the operating system .

More Answers (0)

Categories

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

Tags

Products


Release

R2017b

Community Treasure Hunt

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

Start Hunting!