Search All of the Math Forum:
Views expressed in these public forums are not endorsed by
NCTM or The Math Forum.



Re: convert mwsize * to int *
Posted:
Jan 7, 2013 12:30 PM


"Thomas Meinguet" <thomas.meinguet@skynet.be> wrote in message <kcbl88$de3$1@newscl01ah.mathworks.com>... > I'd like to come back on this topic. This is not a problem of running a 32bit executable on a 64bit environment but a relevant issue for which a clean solution is indispensable. There are powerful precompiled external 64bit libraries whose input are int* pointers as well. The solution I see for the moment is to cast mwIndex (size_t) values into int in new vectors like this: > > const mwIndex *MWrowInd = mxGetIr(prhs[0]); > const mwIndex *MWcolPtr = mxGetJc(prhs[0]); > const int nnz = (int) MWcolPtr[n]; > rowInd = new int[nnz]; > colPtr = new int[n+1]; > for(int i=0; i<nnz; i++) { rowInd[i] = (int)(MWrowInd[i]); } > for(int i=0; i<=n; i++) { colPtr[i] = (int)(MWcolPtr[i]); } > // > Library_run(..., rowInd, colPtr ,...); > > The number nnz of element of rowInd is equal to the number of non zero elements in the matrix prhs[0] here and can be high. The manual cast results in duplicating large data arrays in the memory, in a context where the developer wants to increase the performances ... just to cancel the unsigned feature of size_t. > > There's no way to work around this using the compatibleArrayDims / largeArrayDims of the mex command as the C++ code to pass to mex can be itself generated with a external code generator that can say this  prior to the mex compilation : > > error: argument of type "const mwIndex *" is incompatible with parameter of type "const int *" > > Does someone have a better workaround for this error, not involving inefficient data duplication in the memory?
General comment: If mwIndex is a size_t and you need an int, then your above looping code will still have potential problems if the value overflows an int. What you will probably get is a negative number in your downstream code, which of course is not correct.
Specific comment: If the underlying type of the existing array is different from the expected type of a routine you are using, I don't know what answer you are looking for. You will have to convert & copy the data or use a different routine. And if there is a potential for overflow, then you will have to manually check for this during the conversion instead of blindly letting the compiler/processor wrap such values to negative values (like you do in the above code). On older versions of MATLAB (R2006a and earlier) the Ir and Jc arrays were ints, so there would be no conversion necessary. But on newer versions of MATLAB I don't see any shortcut possible if you want to use the routine that is expecting an int* as input. At the very least, even if mwIndex (size_t) and int are the same size (e.g., both 32bit), to be robust you would have to check the values for int overflow before passing the pointer to the routine.
James Tursa



