To avoid code repetition in mexfunctions you can use this class to convert from the mxArray array passed into mexFunction to c++ native data types. Each method implemented so far checks that the mxArray has the desired type and size and exists. I plan on adding new types as they crop up in our code development, though this initial class could easily be useful if you intend to code more than one mexfunction.
No. You are wrong about the mxGetPr call I noted above. Before you even get to the (bool) cast you do this *mxGetPr(etc). That statement, in and of itself, will access 8 bytes of memory as a double. The (bool) cast comes after that. So it will in fact cause 8 bytes to be used in the conversion to (bool), 7 of which are invalid memory. If you insist on using mxGetPr then you should have done this:
value = *((bool *)mxGetPr(args[argnumber]));
Thanks Jan, James. I will add to the functionality and make it compatible with mxSize.
James, think that mxGetPr is the right fnction to use, it returns the address of the specifed mxArray whatever its type. I then cast it to the type needed. mxGetLogicals works differently.
I will make it consistent re complexity.
1) This line is incorrect in your GetBool method:
value = (bool) *mxGetPr(args[argnumber]);
Since mxGetPr returns a (double *) value, you are dereferencing an 8-byte quantity as a double when in fact there is only a 1-byte quantity there, so you are accessing invalid memory. You should have this instead:
value = (bool) *mxGetLogicals(args[argnumber]);
2) There is an inconsistency with regards to complex variables. E.g., for the GetDoubleArray method you check to see if the input is complex and you throw an error if it is. But in the GetIntArray method you do not check for complexity. I suggest you make all such methods consistent with regards to complexity.
This is a nice idea. Please exapnd it for more types than a scalar LOGICAL, scalar DOUBLE and array of DOUBLES. E.g. other numeric arrays might be valuable, especially if your function would use mxCallMATLAB with the command "double" for converting any numerical input to a double.
In the times of 64 bit environments I'd prefer mxSize instead of int in GetDoubleArray. Please insert the name of the function in the error messages also to make the debugging easier.
Added some more methods for integers and vectors
Download apps, toolboxes, and other File Exchange content using Add-On Explorer in MATLAB.