MATLAB: Does the FORTRAN MEX API function mxCopyPtrToInteger4 return incorrect results on 64-bit MATLAB

largearraydimsMATLABmwpointermwsizemxcopyptrtointeger4mxcopyptrtoptrarray

I am writing a FORTRAN MEX file in which I am using the MEX API function MXCOPYPTRTOINTEGER4 as shown in the line of code below:
call mxCopyPtrToInteger4( mxGetDimensions( PRHS(2) ),
$ DIMS, NDIMW )
where DIMS is INTEGER*4 and NDIMW is MWSIZE. This works fine on a 32-bit MATLAB.
However, when I recompile and execute this MEX file on 64-bit MATLAB, this code snippet gives me erroneous results. It does not provide the correct dimensions of a 2-D cell array or a 3-D matrix.

Best Answer

This issue arises because of the difference in how the FORTRAN pre-compiler interprets mwPointer on 32-bit and 64-bit systems. The FORTRAN preprocessor converts mwPointer to INTEGER*4 when building binary MEX-files on 32-bit platforms and to INTEGER*8 on 64-bit platforms.
The function mxGetDimensions returns an mwPointer. So when using mxCopyPtrToInteger4 to copy the data, you assume that the array size is INTEGER*4 which is not the case on 64-bit platforms.
As a workaround you can follow one of these options:
1) Use the FORTRAN MEX API function MXCOPYPTRTOPTRARRAY as shown below:
call mxCopyPtrToPtrArray(mxGetDimensions( PRHS(2) ),
$ DIMSW, NDIMW)
where DIMSW is MWPOINTER and NDIMW is MWSIZE
2) Compile the MEX file using the "-largeArrayDims" flag in the MEX command.