Linking C++ to Matlab via mex: passing arguments

I need to call C++ code from Matlab. I know I have to write a mex wrapper, but I can't figure out how to pass the arguments correctly.

The C++ function to be called is:

foo(int* n1,int* n2,int* n3,double* x,double* y,int* n4) 

x is matrix on which computations are done, y is an output vector. I am having trouble passing the integer arguments which correspond to the dimensions of the matrix.

I wrote the following wrapper:

void mexFunction(
     int          nlhs,
     mxArray      *plhs[],
     int          nrhs,
     const mxArray *prhs[]
double  *x, *y;
int *n3,*n4;
mwSize nrow,ncols;

  x = mxGetPr(prhs[0]);
  n3 = mxGetPr(prhs[1]);
  n4 = mxGetPr(prhs[2]);
  nrow = mxGetM(prhs[0]);
  ncols = mxGetN(prhs[0]);

  /* Create a matrix for the return argument */ 
  plhs[0] = mxCreateDoubleMatrix(nrow, 1, mxREAL);
  y = mxGetPr(plhs[0]);

  foo(*nrow,*ncols,*n3, x,y,*n4);

However, when I try to compile, the following errors arise:

  • warning C4267: '=' : conversion from 'size_t' to 'mwSize', possible loss of data (n3-n4 line)
  • warning C4267: '=' : conversion from 'size_t' to 'mwSize', possible loss of data (nrow,ncol line)
  • error C2100: illegal indirection (foo line)

I can't seem to figure out how to make this work. Any help would be appreciated.


There are some mistakes, use it like this, you need to cast it to mwSize to avoid warnings:

nrow = (mwSize)mxGetM(prhs[0]);
ncols = (mwSize)mxGetN(prhs[0]);

Anad other change is that pointers are passed using '&' and you don't need to give *n4

foo(&nrow,&ncols,n3, x,y,n4);

warning C4267: '=' : conversion from 'size_t' to 'mwSize', possible loss of data (n3-n4 line)
warning C4267: '=' : conversion from 'size_t' to 'mwSize', possible loss of data (nrow,ncol line)

Here your target variables are smaller than the values returned by the function. Obviously, MATLAB changed the return types of these functions to size_t so you should match your variables as well.

At least, this was my first thought. But I am wrong here: as you are passing (resp. should pass) the addresses of the variables, you should natch them to thetype needed by the function.

error C2100: illegal indirection (foo line)

This is clear: what do you want to achieve with *nrow and *ncols? They are no pointers, so using * is pointless.

Need Your Help

What is the concept behind the "... See more" effect implemented in Facebook iOS app?

ios objective-c facebook ios7 uilabel

As you can see in the photo viewer of the Facebook app, there's a 2-liner truncated label (if the text is too long) with a "... See more" at the end. If "See more" is clicked, the whole text is shown

Trying to filter out invalid URL characters in C regex

c regex string escaping match

I created code here that is supposed to determine if a URL contains an invalid set of characters, and regex may be a good way to go.