MATLAB: Matlab shuts down after executing a mex call

mexshut down

Hi,
I'm calling a C++ function using Mex. The function call works fine. After the file is called and the result is displayed, Matlab shuts down by itself. How do I stop this from happening?

Best Answer

plhs[] is an array that MATLAB creates when you call the mex function to hold the return variables. But MATLAB doesn't create these variables for you, it simply creates a pointer array to hold the pointers to the return variables. You the programmer are expected to create these variables. When you enter the mex function, plhs[] values are not yet pointing to any variables. When you do this:
x = mxGetPr(plhs[0]);
You are asking mxGetPr to get the real data pointer from the variable pointed to by plhs[0], but plhs[0] is an uninitialized pointer, hence the crash. You need to do this:
plhs[0] = mxCreateDoubleMatrix(1, 1, mxREAL); // create the return variable
x = mxGetPr(plhs[0]);
And, as Walter points out, even if you do this as you currently have the code you will get a 0 returned value since you don't assign anything to the output yet via the x pointer. E.g., you could change the last line to this:
*x = test(a,b);
Related Question