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);
  return;
  }

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top