Three comments:
1) You should NEVER, NEVER, NEVER pass literal integers into mex API functions. It can often be the case that your compiler will treat those literal integers as INTEGER*4 type, when in fact the MATLAB version & API library you are linking to is expecting INTEGER*8 type. Arguments are not type promoted in Fortran like they are in C/C++. To avoid this potential problem, always used typed variables to pass arguments into mex API functions using the exact signatures specified in the doc. So this
plhs(1) = mxCreateNumericArray(4,[nx1,nx2,nx3,nx4,nx5,nx6,nx7],myclassid,0)
should be something like this instead
mwSize ndim
integer*4 ComplexFlag
:
ndim = 4
ComplexFlag = 0
plhs(1) = mxCreateNumericArray(ndim,[nx1,nx2,nx3,nx4,nx5,nx6,nx7],myclassid,ComplexFlag)
That being said, the above code doesn't make any sense to me as written. Why are you passing in a 7-element dimension array and telling mxCreateNumericArray that you are only passing in 4 dimensions? Those last three dimensions of nx5, nx6, nx7 will be ignored as the code is currently written, possibly creating a situation where the result is undersized and downstream code will try to access invalid memory and crash. Seems like that first argument should be a 7, not a 4.
2) There are no checks in the code to see if the dimension values passed in actually match the data variables passed in. If there is a mismatch you can easily access invalid memory and crash MATLAB. That is, there are no checks like this in the code:
mwPointer, external :: mxGetNumberOfElements
:
if( mxGetNumberOfElements(prhs(14)) /= nodes ) then
call mexErrMsgTxt("Number of elements mismatch for prhs(14)")
endif
if( mxGetNumberOfElements(prhs(15)) /= nodes ) then
call mexErrMsgTxt("Number of elements mismatch for prhs(15)")
endif
if( mxGetNumberOfElements(prhs(16)) /= nodes ) then
call mexErrMsgTxt("Number of elements mismatch for prhs(16)")
endif
3) You don't have basic checks for input integrity in your code for number and type of inputs. E.g., you should have stuff like this up front (not necessarily an inclusive list):
integer k
:
if( nlhs /= 3 ) then
call mexErrMsgTxt("Need to specify three outputs")
endif
if( nrhs /= 16 ) then
call mexErrMsgTxt("Need 16 full double real inputs")
endif
do k=1,16
if( .not.mxIsDouble(prhs(k)) .or. mxIsSparse(prhs(k)) .or. mxIsComplex(prhs(k)) ) then
call mexErrMsgTxt("All inputs must be full double real")
endif
enddo
Etc.
If the types and sizes and sparsity and complexity etc. are not what the mex routine expects, this can easily crash MATLAB. You should make all of these checks before you access any variables and before you allocate any variables.
Best Answer