I am currently working on porting some C MEX-files for 32-bit Matlab to 64-bit Matlab.
While doing so, I have encountered two types, one coming from the Matlab people, and one which is C standard.
This is what the Matlab documentation is saying about mwSize
:
mwSize
(C and Fortran)Type for size values
Description
mwSize
is a type that represents size values, such as array dimensions. Use this function for cross-platform flexibility. By default,mwSize
is equivalent toint
in C. When using themex -largeArrayDims
switch,mwSize
is equivalent tosize_t
in C. In Fortran,mwSize
is similarly equivalent toINTEGER*4
orINTEGER*8
, based on platform and compilation flags.
This is what Wikipedia is saying about size_t
:
size_t
is an unsigned data type defined by several C/C++ standards (e.g., the C99 ISO/IEC 9899 standard) that is defined instddef.h
.[1] It can be further imported by inclusion ofstdlib.h
as this file internally sub includesstddef.h
[2].This type is used to represent the size of an object. Library functions that take or return sizes expect them to be of this type or have the return type of
size_t
. Further, the most frequently used compiler-based operatorsizeof
should evaluate to a value that is compatible withsize_t
.The actual type of
size_t
is platform-dependent; a common mistake is to assumesize_t
is the same asunsigned int
, which can lead to programming errors,[3][4] when moving from 32 to 64-bit architecture, for example.
As far as I can see, these types are actually the same. My questions are:
mwSize
, but I am not sure.Edit: I should add that the Matlab people are using both. For example:
size_t mxGetN(const mxArray *pm);
is a function that is retrieving the number of columns of an mxArray. However, when one creates a matrix, one uses,
mxArray *mxCreateDoubleMatrix(mwSize m, mwSize n, mxComplexity ComplexFlag);
where the input evidently should be mwSize.
mwSize
is defined for backward compatibility and portability. As the documentation states, it maps to an int
when the -largeArrayDims
switch is not used during compilation, and size_t
when it is. So, in the first case mwSize
is signed, but in the second, it isn't.
Using mwSize
in your code allows you to re-use the code on all platforms, irrespective of whether that flag is used or not.
As for the API inconsistencies you've pointed out, they are truly inconsistencies, but not ones for major concern. mxGetN()
will never return a negative number, so having it return a size_t
is OK. However, (I'm guessing) older versions or versions of the mex API on certain platforms expect an int to passed to mxCreateDoubleMatrix()
so defining the function as taking an input of type mwSize
makes it portable and / or backward compatible.
Short answer is, use mwSize
and use -largeArrayDims
to compile the mex function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With